当咱们写React时,咱们老是经过改变State和传递Prop对view进行控制,有时,也会遇到一点小麻烦。javascript
可是随着咱们的应用变的愈来愈复杂,组件嵌套也变的愈来愈深,有时甚至要从最外层将一个数据一直传递到最里层(好比当前user的信息)。java
理论上,经过prop一层层传递下去固然是没问题的。不过这也太麻烦啦,要是能在最外层和最里层之间开一个穿越空间的虫洞就行了。redux
幸运的是,React的开发者也意识到这个问题,为咱们开发出了这个空间穿越通道 —— Context。session
看起来很高大上的Context使用起来却异常简单。less
假设咱们有下面这样的组件结构。组件化
D组件须要获取在A组件中用户信息应该怎么办?有了Context,咱们能够这么作。ui
// Component A class A extends React.Component { // add the following method getChildContext() { return { user: this.props.user } } render() { return <div>{this.props.children}</div> } } // add the following property A.childContextTypes = { user: React.PropTypes.object.isRequired } // Component D class D extends React.Component { render() { return <div>{this.context.user.name}</div> } } // add the following property D.contextTypes = { user: React.PropTypes.object.isRequired }
很简单吧,只要在外层定义一个getChildContext
方法,在父层和里层分别制定contextTypes
就能够直接在里层用this.context
访问了,是否是很厉害,XDthis
根据官方的文档,Context在如下的lifecycle方法中也是可使用的spa
void componentWillReceiveProps( object nextProps, object nextContext ) boolean shouldComponentUpdate( object nextProps, object nextState, object nextContext ) void componentWillUpdate( object nextProps, object nextState, object nextContext ) void componentDidUpdate( object prevProps, object prevState, object prevContext )
同时,在最新的stateless组件中,也是可使用Context的,并且更加简单。code
function D(props, context) { return ( <div>{this.context.user.name}</div> ); } D.contextTypes = { user: React.PropTypes.object.isRequired }
既然Context使用起来如此方便,是否是就应该多多用它呢?
显然,抛开Context还处于刚刚公开,API不稳定不说,即便对于组件化的开发,处处用也不是一个好主意。
Context就像javascript中的全局变量,只有真正全局的东西才适合放在context中。
好比:
因此,当发现使用Context仅仅为了少打几个字而不考虑存放何种数据,那极可能用错Context了……