redux provider源码解析
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
provider 源碼
import { Component, Children } from 'react' import PropTypes from 'prop-types' import storeShape from '../utils/storeShape' import warning from '../utils/warning' let didWarnAboutReceivingStore = falsefunction warnAboutReceivingStore() {if (didWarnAboutReceivingStore) {return}didWarnAboutReceivingStore = truewarning('<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 } = thisconst { store: nextStore } = nextPropsif (store !== nextStore) {warnAboutReceivingStore()}} }Provider.propTypes = {store: storeShape.isRequired,children: PropTypes.element.isRequired } Provider.childContextTypes = {store: storeShape.isRequired }首先學(xué)習(xí)react數(shù)據(jù)傳遞三種方法,props,state,context
props:一般用于將父組件數(shù)據(jù)傳遞到子組件,不能跨組件傳遞
state:state是內(nèi)部狀態(tài)或者局部狀態(tài)
? ? ? ? ? ?es6數(shù)據(jù)解析操作,let {xxx ,xx, x} = this.state;
context: 和props相比,context可以跨組件傳遞信息
聲明context步驟一:
constructor(props, context) {super(props, context)this.store = props.store}getChildContext() {return { store: this.store }}更具react生命周期,首先constructor方法獲取屬性store,getChildContext()將store放入context中
步驟二:
Provider.propTypes = {store: storeShape.isRequired,children: PropTypes.element.isRequired }驗(yàn)證組件信息
步驟三:
Provider.childContextTypes = {store: storeShape.isRequired }聲明了childrenContextTypes。如果不聲明的話,將無(wú)法在組件中使用getChildContext()方法;
獲取context:
子樹(shù)中的任何組件都可以通過(guò)定義ContextTypes?去訪問(wèn)它。
connect中通過(guò)
? Connect.contextTypes = {store: storeShape}然后通過(guò)constructor獲取store?
constructor(props, context) {super(props, context)this.version = versionthis.store = props.store || context.storeconst storeState = this.store.getState()this.state = { storeState }this.clearCache()}最后執(zhí)行render渲染,返回一個(gè)react子元素。Children.only是react提供的方法,this.props.children表示的是只有一個(gè)root的元素。
轉(zhuǎn)載于:https://my.oschina.net/u/3647713/blog/1535249
總結(jié)
以上是生活随笔為你收集整理的redux provider源码解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mybatis的延迟加载
- 下一篇: 初识RESTful