redux provider源码解析

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的元素。

相关文章
相关标签/搜索