React中的“虫洞”——Context

前端之家收集整理的这篇文章主要介绍了React中的“虫洞”——Context前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

背景

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

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

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

使用

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

基本使用

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

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

  1. // Component A
  2. class A extends React.Component {
  3. // add the following method
  4. getChildContext() {
  5. return {
  6. user: this.props.user
  7. }
  8. }
  9. render() {
  10. <div>{this.props.children}</div>
  11. }
  12. }
  13. // add the following property
  14. A.childContextTypes = {
  15. user: React.PropTypes.object.isrequired
  16. }
  17.  
  18.  
  19. // Component D
  20. class D extends React.Component {
  21. render() {
  22. <div>{this.context.user.name}</div>
  23. }
  24. }
  25. // add the following property
  26. D.contextTypes = {
  27. user: React.PropTypes.object.isrequired
  28. }

很简单吧,只要在外层定义一个getChildContext方法,在父层和里层分别制定contextTypes就可以直接在里层用this.context访问了,是不是很厉害,XD

在lifecycle方法中使用

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

  1. void componentWillReceiveProps(
  2. object nextProps,object nextContext
  3. )
  4.  
  5. boolean shouldComponentUpdate(
  6. object nextProps,object nextState,object nextContext
  7. )
  8.  
  9. void componentWillUpdate(
  10. object nextProps,object nextContext
  11. )
  12.  
  13. void componentDidUpdate(
  14. object prevProps,object prevState,object prevContext
  15. )

stateless组件中使用

同时,在最新的stateless组件中,也是可以使用Context的,而且更加简单。

  1. function D(props,context) {
  2. return (
  3. <div>{this.context.user.name}</div>
  4. );
  5. }
  6. D.contextTypes = {
  7. user: React.PropTypes.object.isrequired
  8. }

使用场景

既然Context使用起来如此方便,是不是就应该多多用它呢?
显然,抛开Context还处于刚刚公开,API不稳定不说,即使对于组件化的开发,到处用也不是一个好主意。
Context就像javascript中的全局变量,只有真正全局的东西才适合放在context中。

比如:

  • 当前用户信息

  • flux、redux的store

  • session级别信息(语言,主题等)

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

猜你在找的React相关文章