實現簡單的 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
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章