react-redux中的Provider组件

作者: 7天苹果 | 来源:发表于2017-05-03 15:22 被阅读9453次
Provider

Provider功能主要为以下两点:

  • 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
  • 接收Redux的store作为props,通过context对象传递给子孙组件上的connect

核心代码很精简:


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
}
  • 首先,对原组件进行了封装: render方法中, 渲染了其子级元素, 使整个应用成为Provider的子组件。

    (1)this.props.childern用于获取当前组件的所有子组件
    (2)Children为react内部定义的顶级对象, 该对象封装了一些方便操作字组件的方法. Children.only用于获取仅有的一个子组件,没有或者超过一个均会报错. 所以注意: 确保Provider组件的直接子级为单个封闭元素,切勿多个组件平行放置

  • 其次,传递store
    (1)constructor方法: Provider初始化时, 获取到props中的store对象;
    (2) getChildContext方法: 将外部的store对象放入context对象中,使子孙组件上的connect可以直接访问到context对象中的store。

注: context可以使子孙组件直接获取父级组件中的数据或方法,而无需一层一层通过props向下传递。context对象相当于一个独立的空间,父组件通过getChildContext()向该空间内写值;定义了contextTypes验证的子孙组件可以通过this.context.xxx,从context对象中读取xxx字段的值。

使用实例

之前研究connect的原理时写了一个计数器,现在我们可以将其中的Provider组件写成源码的形式使用,在具体环境下能更好地理解它地原理和效果,具体代码请看:
https://github.com/lipeishang/react-redux-provider-demo

相关文章

  • React-redux

    安装 npm install react-redux --save Provider Provider组件放在应用...

  • Provider高阶组件

    Provider provider是react-redux提供的一个高阶组件 使用Provider的简单步骤: 创...

  • React Native redux理解

    React-redux提供Provider和connect两个接口链接 Provider组件在应用最外层,传入st...

  • RN:Redux、React-Redux实践之更换主题色

    为App根组件包裹Provider组件,以便整个项目能使用Redux和React-Redux 上一篇文章中,我们说...

  • 实现基于react-redux的状态管理库

    react-redux是基于context的特性实现了父子组件的状态共享,查看组件Provider源码我们可以发现...

  • react-redux中的Provider组件

    Provider功能主要为以下两点: 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件 接收Re...

  • mini-react-redux的实现

    ` react-redux的原理 提供一个Provider组件 负责吧外层的数据 传递给所有的子组件 connec...

  • react-router路由守卫

    安装redux和react redux index.js 用react-redux的Provider复合组件实现逐...

  • react-redux

    使用React-Redux时,首先要创建一个Provider组件,作为最顶层的组件将所有React组件包裹起来,从...

  • react-redux provider组件

    provider组件概念图 provider组件的作用 provider包裹在根组件外层,使所有的子组件都可以拿到...

网友评论

    本文标题:react-redux中的Provider组件

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