您的位置:首页 > Web前端 > React

实现简单的 react-redux

2017-09-27 10:12 615 查看
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

來源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: