react redux - Provider

什么是Provider

最简单的就是 提供store

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

<Provider store={store}>
        <Router history={browserHistory}>
            <Route path="/" component={App}>
                <IndexRoute component={Home}/>
            </Route>
        </Router>
</Provider>

详解

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的子组件
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容