react-redux是为react而生的,是为了在react项目中能够更方便的使用redux,所以有了react-redux这个库。
context.js是跨级通信的对象,通过react.createContext创建
import React from 'react';
const ReduxContext = React.createContext(null);
export default ReduxContext;
Provider.js是一个组件是相当于提供商,提供redux库中store对象。
import React, { Component } from 'react'
import ReduxContext from './context';
export default class Provider extends Component {
render() {
return (
<ReduxContext.Provider value={{store:this.props.store}}>
{this.props.children}
</ReduxContext.Provider>
)
}
}
connect.js是用来将组件与redux之间进行一个关联,并将每个组件公共的代码提取出来。connect.js通过store对象的getState函数获取公共仓库state对象,订阅store对象通过setState函数实时更新组件本地状态,通过redux的bindActionCreators函数将action进行自动绑定到dispatch上。
import React,{Component} from 'react';
import {bindActionCreators} from '../redux';
import ReactContext from './context.js';
export default function(mapStateToProps,mapDispatchToProps){
return function(WrappendComponent){
return class extends Component{
static contextType=ReactContext;
constructor(props,context){
super(props);
this.state=mapStateToProps(context.store.getState());
}
componentDidMount(){
this.unsubscribe=this.context.store.subscribe(()=>{
this.setState(mapStateToProps(this.context.store.getState()))
})
};
componentWillUnmount(){
this.unsubscribe();
}
render(){
let actions={};
if(typeof mapDispatchToProps==='function'){
actions=mapDispatchToProps(this.context.store.dispatch);
}else{
actions=bindActionCreators(mapDispatchToProps,this.context.store.dispatch);
}
return (
<WrappendComponent {...this.state} {...actions}></WrappendComponent>
)
}
}
}
}