美文网首页
react redux - Provider

react redux - Provider

作者: LYF闲闲闲闲 | 来源:发表于2017-05-15 18:40 被阅读981次

什么是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的子组件

相关文章

网友评论

      本文标题:react redux - Provider

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