react redux - Provider

什么是Provider

最简单的就是 提供store

一般我们这样写在代码里,在我们的组件之外用Provider包裹起来,作用就是为了让里面的组件能够获取到store的值


        
            
                
            
        

详解

export default class Provider extends Component {
  getChildContext() { // getChildContext: 将store传递给子孙component
    return { store: this.store }
  }

  constructor(props, context) {
    super(props, context)
    this.store = props.store
  }

  componentWillReceiveProps(nextProps) {
    const { store } = this
    const { store: nextStore } = nextProps

    if (store !== nextStore) {
      warnAboutReceivingStore()
    }
  }

  render() {
    let { children } = this.props
    return Children.only(children)
  }
}
  • 使用react的context属性,可以将属性(props)直接给子孙component,无须通过props层层传递。
  • getChildContext : 将外部的store对象放入context对象中,使子孙组件上的connect可以直接访问到context对象中的store。
  • constructor :初始化获得了props中的store
  • render : 渲染了其子级元素, 使整个应用成为Provider的子组件

你可能感兴趣的:(react redux - Provider)