首页 > 代码库 > React Context

React Context

React Context

1、Why Not To Use Context

  The vast majority of applications do not need to use context.

  大多数应用不需要使用context。

  If you want your application to be stable, don‘t use context. It is an experimental API and it is likely to break in future releases of React.

  context是一个Experimental API,在未来可能会失效。

  It is far more likely that Redux is the right solution to your problem than that context is the right solution.

  Redux是比context更好的方案。

  

2、通过在父类定义getChildContext,则所有的子类都能获得context。

  技术分享技术分享

  By adding childContextTypes and getChildContext to MessageList (the context provider), React passes the information down automatically and any component in the subtree (in this case, Button) can access it by defining contextTypes.

  If contextTypes is not defined, then context will be an empty object.

  如果contextTypes没有定义,则context将会是一个empty object。 

3、Referencing Context in Lifecycle Methods

  If contextTypes is defined within a component, the following lifecycle methods will receive an additional parameter, the context object:

  • constructor(props, context)
  • componentWillReceiveProps(nextProps, nextContext)
  • shouldComponentUpdate(nextProps, nextState, nextContext)
  • componentWillUpdate(nextProps, nextState, nextContext)
  • componentDidUpdate(prevProps, prevState, prevContext)

参考:https://facebook.github.io/react/docs/context.html

React Context