15 react-redux provider组件

provider组件概念图:

provider组件的作用:

  • provider包裹在根组件外层,使所有的子组件都可以拿到state.
 
  • 它接受store作为props,然后通过context往下传,这样react中任何组件都可以通过context获取store。

provider组件的原理:

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)
  }
}

Provider.propTypes = {
  store: storeShape.isRequired,
  children: PropTypes.element.isRequired
}

Provider.childContextTypes = {
  store: storeShape.isRequired
}

关键点在:getChildContext,保存了全局唯一的store,类似于全局变量,子组件后续可以通过this.context.store来访问。

通过context传递属性的方式可以大量减少通过props 逐层传递属性的方式,可以减少组件之间的直接依赖关系。



原文地址:https://www.cnblogs.com/liufei1983/p/14537528.html