上篇文章已经说了,provider主要的作用就是将外界传入的store设置成可以通过this.context获取。 所以它的实现方式也比较简单:
主要就是定义childContextTypes,还有getChildContext。
export function createProvider(storeKey = 'store', subKey) {
const subscriptionKey = subKey || `${storeKey}Subscription`
class Provider extends Component {
getChildContext() {
// 在这里将它赋值给this.context
return { [storeKey]: this[storeKey], [subscriptionKey]: null }
}
constructor(props, context) {
super(props, context)
// 将外面传入的store赋值给this.store
this[storeKey] = props.store;
}
render() {
// Children.only用于获取仅有的一个子组件,多过或者少一一个都会报错
return Children.only(this.props.children)
}
}
if (process.env.NODE_ENV !== 'production') {
Provider.prototype.componentWillReceiveProps = function (nextProps) {
if (this[storeKey] !== nextProps.store) {
warnAboutReceivingStore()
}
}
}
Provider.propTypes = {
store: storeShape.isRequired,
children: PropTypes.element.isRequired,
}
Provider.childContextTypes = {
[storeKey]: storeShape.isRequired,
[subscriptionKey]: subscriptionShape,
}
return Provider
}