原理就是把 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>
}
}