前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React-Redux源码解析(二) -- Provider

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

作者头像
IMWeb前端团队
发布2017-12-29 18:23:05
5350
发布2017-12-29 18:23:05
举报
文章被收录于专栏:IMWeb前端团队IMWeb前端团队

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

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

代码语言:javascript
复制
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() {
         // Children.only用于获取仅有的一个子组件,多过或者少一一个都会报错
          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
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档