react-redux 理解第一篇Provider 组件

先看一下原码

let didWarnAboutReceivingStore = false
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.displayName = 'Provider'

Provider 组件可以说是非常简单只做了三件事

  • reduxcreateStore 函数所创建出来的 store 声明到全局的 context中的并挂载
  • 返回自己的 children 组件,且 children 组件只有有一个,不能是数组。
  • componentWillReceiveProps 中监视 store 的变化,如果重新传了一个 store 则抛出异常。在 redux 的理念里,全局只能有一个 store,且不能改变 store 的引用。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容