先看一下原码
let didWarnAboutReceivingStore = false
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.displayName = 'Provider'
Provider 组件可以说是非常简单只做了三件事
- 把
redux中createStore函数所创建出来的store声明到全局的context中的并挂载 - 返回自己的
children组件,且children组件只有有一个,不能是数组。 - 在
componentWillReceiveProps中监视store的变化,如果重新传了一个store则抛出异常。在redux的理念里,全局只能有一个store,且不能改变store的引用。