React中的“虫洞”——Context

发布时间:2019-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React中的“虫洞”——Context脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

当我们写React时,我们总是通过改变State和传递Prop对view进行控制,有时,也会遇到一点小麻烦。

背景

但是随着我们的应用变的越来越复杂,组件嵌套也变的越来越深,有时甚至要从最外层将一个数据一直传递到最里层(比如当前user的信息)。

理论上,通过PRop一层层传递下去当然是没问题的。不过这也太麻烦啦,要是能在最外层和最里层之间开一个穿越空间的虫洞就好了。

幸运的是,React开发者也意识到这个问题,为我们开发出了这个空间穿越通道 —— Context。

使用

看起来很高大上的Context使用起来却异常简单

基本使用

假设我们有下面这样的组件结构。

React中的“虫洞”——Context

D组件需要获取在A组件中用户信息应该怎么办?有了Context,我们可以这么做。

// 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访问了,是不是很厉害,XD

在lifecycle方法中使用

根据官方的文档,Context在以下的lifecycle方法中也是可以使用的

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组件中使用

同时,在最新的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中。

比如:

  • 当前用户信息
  • flux、redux的Store
  • session级别信息(语言,主题等)

所以,当发现使用Context仅仅为了少打几个字而不考虑存放何种数据,那很可能用错Context了……

脚本宝典总结

以上是脚本宝典为你收集整理的React中的“虫洞”——Context全部内容,希望文章能够帮你解决React中的“虫洞”——Context所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。