上篇文章已经说了,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() { 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 }原文链接:https://www.f2er.com/react/302302.html