通过context传递数据,从provider组建中的props获取state,传给connect 高阶组件,使用高阶组件连接 connect.js
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) : {} let dispatchProps = mapDispatchToProps ? mapDispatchToProps(store.dispatch, this.props) : {} //dispatch this.setState({ allProps: { // 整合普通的 props 和从 state 生成的 props ...stateProps, ...dispatchProps, ...this.props } }) } render () { return <WrappedComponent {...this.state.allProps} /> } } return Connect }provider.js
import React, { Component } from 'react' import PropTypes from 'prop-types' export class Provider extends Component { static propTypes = { children: PropTypes.any } static childContextTypes = { store: PropTypes.object } getChildContext () { return { store: this.props.store } } render () { return ( <div>{this.props.children}</div> ) } }