美文网首页
react-redux简单实现

react-redux简单实现

作者: Mr无愧于心 | 来源:发表于2019-03-14 06:55 被阅读0次

Provider组件的实现

  • 1.接收通过属性传进来的store,把store挂载到上下文当中,当前项目中任何一个组建中,想要使用redux的store,直接通过上下文获取即可
  • 2.在组件的render中,把传递给provider的子元素渲染
class Provider extends React.Component {
    //设置上下文信息类型
    static childContextTypes={
        store:PropTypes.object,
    }
    //设置上下文信息
    getChildContext(){
        return this.props.store;
    }

    constructor(props,context){
        super(props,context);
    }
    render(){
        return this.props.children;
    }
}

connect函数的实现

  • 返回一个函数,返回的函数执行,返回一个新的组件Proxy
  • 把mapStateToProps,mapDispatchToProps执行的结果都当做属性挂载到新的组件上
  • 执行subscribe函数 触发组件的更新
function connect(mapStateToProps,mapDispatchToProps){
    return function (Component){
        return class Proxy entends React.Component{
            //获取上下文的store
            static contextTypes={
                store:PropTypes.object;
            }
            constructor(props,context){
                super(props,context);
                this.state=this.queryProps()//把所有返回值赋值给组件的 状态 用于传递给组件
            }
            conponentDidMount(){//组件渲染结束后,当状态改变,重新获取最新的状态信息,重新把component渲染,把新的状态信息通过属性传递给component
                this.context.store.subscribe(()=>{
                    this.setState(this.queryProps());
                })
            }
            render(){
                return <Component {...this.state}></Component>
            }
            //执行mapStateToProps,mapDispatchToProps,拿到所有返回值,合并成一个新对象
            queryProps(){
                let store=this.context.store;
                let mapState=typeof mapStateToProps == 'function'?mapStateToProps(store.getState()):{};
                let mapDispatch=typeof mapDispatchToProps == 'function'?mapDispatchToProps(store.dispatch):null;
                return {...mapState,...mapDispatch}
            }
        }
    }
}

相关文章

网友评论

      本文标题:react-redux简单实现

      本文链接:https://www.haomeiwen.com/subject/nxhtmqtx.html