Provider

Provider做的事情很简单,跟我们刚才做的核心功能上差不多:利用context给子元素隐式传递store. 这个store被作为属性传入。

我们来看下源码

export default class Provider extends Component {
  getChildContext() {
    return { store: this.store, storeSubscription: null }  
    // Offering unsubscribe method, and isSubscribed information 
    // => storeSubscription, for later unsubscription use in some child.
  }

  constructor(props, context) {
    super(props, context) // Allow component (provider) nested
    this.store = props.store // <Provider store={store gose here}> {children} </Provider>
  }

  render() {
    return Children.only(this.props.children)
    // See https://facebook.github.io/react/docs/react-api.html#react.children.only
    // Returns the only child in children. Throws otherwise.
    // So inside Provider must only have one child
  }
}

if (process.env.NODE_ENV !== 'production') {
  Provider.prototype.componentWillReceiveProps = function (nextProps) {
    const { store } = this
    const { store: nextStore } = nextProps

    if (store !== nextStore) {
      warnAboutReceivingStore()
    }
  }
}

Provider.propTypes = {   
  // In newest version, propTypes is deprecated, will be moved in next version.
  // For library minification consideration, propTypes now is surpported by standalone library 'prop-types'
  // See https://www.npmjs.com/package/prop-types
  store: storeShape.isRequired,
  children: PropTypes.element.isRequired
}

Provider.childContextTypes = {
  store: storeShape.isRequired,
  storeSubscription: subscriptionShape
}

Provider.displayName = 'Provider'

// Comment by @kylewh 4.16.2019
// About storeShape
export const storeShape = PropTypes.shape({
  subscribe: PropTypes.func.isRequired,
  dispatch: PropTypes.func.isRequired,
  getState: PropTypes.func.isRequired
})

// About subscriptionShape
export const subscriptionShape = PropTypes.shape({
  trySubscribe: PropTypes.func.isRequired,
  tryUnsubscribe: PropTypes.func.isRequired,
  notifyNestedSubs: PropTypes.func.isRequired,
  isSubscribed: PropTypes.func.isRequired,
})

对于我们的demo,只需要删去我们定义的Provider,引入redux:

const { Provider } = ReactRedux

但如我们先前所说,使用context是官方不推荐的,这种方式在封装整体性上也略显蹩脚。

于是react-redux又提供了connect

下一节我们将进行分析和应用.

results matching ""

    No results matching ""