provider 源碼javascript
import { Component, Children } from 'react' import PropTypes from 'prop-types' import storeShape from '../utils/storeShape' import warning from '../utils/warning' let didWarnAboutReceivingStore = false function warnAboutReceivingStore() { if (didWarnAboutReceivingStore) { return } didWarnAboutReceivingStore = true warning( '<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/reactjs/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.' ) } export default class Provider extends Component { getChildContext() { return { store: this.store } } constructor(props, context) { super(props, context) this.store = props.store } render() { return Children.only(this.props.children) } } if (process.env.NODE_ENV !== 'production') { Provider.prototype.componentWillReceiveProps = function (nextProps) { const { store } = this const { store: nextStore } = nextProps if (store !== nextStore) { warnAboutReceivingStore() } } } Provider.propTypes = { store: storeShape.isRequired, children: PropTypes.element.isRequired } Provider.childContextTypes = { store: storeShape.isRequired }
首先學習react數據傳遞三種方法,props,state,contextjava
props:通常用於將父組件數據傳遞到子組件,不能跨組件傳遞react
state:state是內部狀態或者局部狀態
es6數據解析操做,let {xxx ,xx, x} = this.state;git
context: 和props相比,context能夠跨組件傳遞信息es6
聲明context步驟一:github
constructor(props, context) { super(props, context) this.store = props.store } getChildContext() { return { store: this.store } }
更具react生命週期,首先constructor方法獲取屬性store,getChildContext()將store放入context中redux
步驟二:ide
Provider.propTypes = { store: storeShape.isRequired, children: PropTypes.element.isRequired }
驗證組件信息學習
步驟三:ui
Provider.childContextTypes = { store: storeShape.isRequired }
聲明瞭childrenContextTypes。若是不聲明的話,將沒法在組件中使用getChildContext()方法;
獲取context:
子樹中的任何組件均可以經過定義ContextTypes 去訪問它。
connect中經過
Connect.contextTypes = { store: storeShape }
而後經過constructor獲取store
constructor(props, context) { super(props, context) this.version = version this.store = props.store || context.store const storeState = this.store.getState() this.state = { storeState } this.clearCache() }
最後執行render渲染,返回一個react子元素。Children.only是react提供的方法,this.props.children表示的是隻有一個root的元素。