当我们写React时,我们总是通过改变State和传递Prop对view进行控制,有时,也会遇到一点小麻烦。
背景
但是随着我们的应用变的越来越复杂,组件嵌套也变的越来越深,有时甚至要从最外层将一个数据一直传递到最里层(比如当前user的信息)。
理论上,通过prop一层层传递下去当然是没问题的。不过这也太麻烦啦,要是能在最外层和最里层之间开一个穿越空间的虫洞就好了。
幸运的是,React的开发者也意识到这个问题,为我们开发出了这个空间穿越通道 —— Context。
使用
看起来很高大上的Context使用起来却异常简单。
基本使用
假设我们有下面这样的组件结构。
D组件需要获取在A组件中用户信息应该怎么办?有了Context,我们可以这么做。
- // Component A
- class A extends React.Component {
- // add the following method
- getChildContext() {
- return {
- user: this.props.user
- }
- }
- render() {
- <div>{this.props.children}</div>
- }
- }
- // add the following property
- A.childContextTypes = {
- user: React.PropTypes.object.isrequired
- }
- // Component D
- class D extends React.Component {
- render() {
- <div>{this.context.user.name}</div>
- }
- }
- // add the following property
- D.contextTypes = {
- user: React.PropTypes.object.isrequired
- }
很简单吧,只要在外层定义一个getChildContext
方法,在父层和里层分别制定contextTypes
就可以直接在里层用this.context
访问了,是不是很厉害,XD
在lifecycle方法中使用
根据官方的文档,Context在以下的lifecycle方法中也是可以使用的
- void componentWillReceiveProps(
- object nextProps,object nextContext
- )
- boolean shouldComponentUpdate(
- object nextProps,object nextState,object nextContext
- )
- void componentWillUpdate(
- object nextProps,object nextContext
- )
- void componentDidUpdate(
- object prevProps,object prevState,object prevContext
- )
stateless组件中使用
同时,在最新的stateless组件中,也是可以使用Context的,而且更加简单。
- 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了……