當咱們寫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了……