加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React-Redux源码解析(二) -- Provider

发布时间:2020-12-15 06:40:32 所属栏目:百科 来源:网络整理
导读:上篇文章已经说了,provider主要的作用就是将外界传入的store设置成可以通过this.context获

上篇文章已经说了,provider主要的作用就是将外界传入的store设置成可以通过this.context获取。
所以它的实现方式也比较简单:

主要就是定义childContextTypes,还有getChildContext。

export function createProvider(storeKey = 'store',subKey) {
    const subscriptionKey = subKey || `${storeKey}Subscription`
      
    class Provider extends Component {
        getChildContext() {
          // 在这里将它赋值给this.context
          return { [storeKey]: this[storeKey],[subscriptionKey]: null }
        }

        constructor(props,context) {
          super(props,context)
          // 将外面传入的store赋值给this.store
          this[storeKey] = props.store;
        }

        render() {
          return Children.only(this.props.children)
        }
    }

    if (process.env.NODE_ENV !== 'production') {
      Provider.prototype.componentWillReceiveProps = function (nextProps) {
        if (this[storeKey] !== nextProps.store) {
          warnAboutReceivingStore()
        }
      }
    }

    Provider.propTypes = {
        store: storeShape.isRequired,children: PropTypes.element.isRequired,}
    Provider.childContextTypes = {
        [storeKey]: storeShape.isRequired,[subscriptionKey]: subscriptionShape,}

    return Provider
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读