美文网首页
react-redux 理解第一篇Provider 组件

react-redux 理解第一篇Provider 组件

作者: happy_milo | 来源:发表于2018-12-25 16:26 被阅读0次

    先看一下原码

    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 的引用。

    相关文章

      网友评论

          本文标题:react-redux 理解第一篇Provider 组件

          本文链接:https://www.haomeiwen.com/subject/tfiflqtx.html