实现简单的 react-redux

http://www.jianshu.com/p/26bb9a27c77a?utm_campaign=maleskine&utm_content=note&utm_medium=pc_all_hots&utm_source=recommendation


原理就是把 redux 的 store,放在 react 的 context 里

React.js 的 context
动手实现 React-redux(一):初始化工程
动手实现 React-redux(二):结合 context 和 store
动手实现 React-redux(三):connect 和 mapStateToProps
动手实现 React-redux(四):mapDispatchToProps
动手实现 React-redux(五):Provider
动手实现 React-redux(六):React-redux 总结

import React,{Component} from 'react';
import PropTypes from 'prop-types';

export const connect = (mapStateToProps,mapDispatchToProps) => (WrappedComponent) => {
    class Connect extends Component {
        static contextTypes = {
            store: PropTypes.object
        };

        constructor() {
            super();
            this.state = {
                allProps: {}
            }
        }

        componentWillMount() {
            const {store} = this.context;
            this._updateProps();
            store.subscribe(() => {
                this._updateProps();
            })
        }

        _updateProps() {
            const {store} = this.context;
            let stateProps = mapStateToProps ? mapStateToProps(store.getState(),this.props) : {}; // 额外传入 props,让获取数据更加灵活方便
            let dispatchProps = mapDispatchToProps ? mapDispatchToProps(store.dispatch,this.props) : {};
            this.setState({
                allProps: { // 整合普通的 props 和从 state 生成的 props
                    ...stateProps,...dispatchProps,...this.props
                }
            })
        }

        render() {
            return <WrappedComponent {...this.state.allProps}/>;
        }
    }
    return Connect;
};

export class Provider extends Component {
    static propTypes = {
        store: PropTypes.object,children: PropTypes.any
    };

    static childContextTypes = {
        store: PropTypes.object
    };

    getChildContext() {
        return {
            store: this.props.store
        }
    }

    render() {
        return <div>
            {this.props.children}
        </div>
    }
}
作者:waka 链接:http://www.jianshu.com/p/26bb9a27c77a 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...