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了……

    原文作者:BetaRabbit
    原文地址: https://segmentfault.com/a/1190000004636213
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞