React中,通过React组件可以很容易地追踪数据流。当你关注一个组件,你可以发现哪一个props被传递了,这样使得你的应用很容被推断。

在一些情况下,你想要传递数据通过组件树而不需要去手动在每一层传递。你可以直接使用强大的context API。

为什么不使用context

大量的应用不需要使用context。

如果你希望你的应用稳定,不要使用context。这是一个实验性的API在未来的版本中有可能会崩溃。

如果你不熟悉state管理库就类似于Redux或者Mobx,不要使用context。对于很多实际的应用,这些库和它们的React绑定实现是很好的选择来管理state,这对于很多组件都有重大意义。解决问题最好的方案更像是Redux而不是context。

如果你不是一个有经验的React开发者,不要使用context。有更好的方式去实现功能通过使用props和state。

如果你坚持使用context而不管这些警告,那么就请试图隔离你使用context在一个较小的范围并且避免直接使用context API为了当API改变的时候升级方便。

怎样使用context

假设你拥有这样的一个结构:

class Button extends React.Component {
render() {
return (
<button style={{background: this.props.color}}>
{this.props.children}
</button>
);
}
} class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button color={this.props.color}>Delete</Button>
</div>
);
}
} class MessageList extends React.Component {
render() {
const color = "purple";
const children = this.props.messages.map((message) =>
<Message text={message.text} color={color} />
);
return <div>{children}</div>;
}
}

在这个例子里,我们手动传递了一个color属性为了让Button和Message组件的有一个合适的样式。使用context,我们可以自动传递属性通过树。

class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
} Button.contextTypes = {
color: React.PropTypes.string
}; class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
} class MessageList extends React.Component {
getChildContext() {
return {color: "purple"};
} render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
} MessageList.childContextTypes = {
color: React.PropTypes.string
};

通过为MessageList组件(context提供者)添加childContextTypes属性和getChildContext方法,React会自动传递信息并且任何子树里的组件(在这个例子,Button组件)都可以获取到这个信息通过定义contextTypes。

如果contextTypes没有定义,那么context会是一个空对象。

父子联合

context也可以让你建造一套可以让父组件和子组件通信的API。举个例子,一个这样运作的库叫做React Router v4

import { Router, Route, Link } from 'react-router-dom';

const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul> <hr /> <Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);

通过从Router组件传递一些信息,每一个Link和Route都可以和包含的Router通信。

在你使用类似的API创建组件的时候,思考是否有更灵活的替代方案。举个例子,你可以传递整个React组件作为props如果你喜欢。

在生命周期方法里引用context

如果在一个组件内部定义了contextTypes,下面的生命周期方法将会接收一个额外的参数,就是context对象:

  • constructor(props, context)
  • componentWillReceiveProps(nextProps, nextContext)
  • shouldComponentUpdate(nextProps, nextState, nextContext)
  • componentWillUpdate(nextProps, nextState, nextContext)
  • componentDidUpdate(prevProps, prevState, prevContext)

在无状态的函数式组件里引用context

如果在函数里定义了contextTypes作为一个属性,那么也可以在无状态的函数式组件里引用context。下面的代码显示了一个Button组件被写成一个无状态函数式组件。
const Button = ({children}, context) =>
<button style={{background: context.color}}>
{children}
</button>; Button.contextTypes = {color: React.PropTypes.string};

更新context

不要这样做。

React有一个更新context的API,但是它实质上已经损坏你不应该使用它。

getChildContext函数当props或者state改变的时候会被调用。为了在context中更新数据,使用this.setState来触发本地的state更新。这样将会触发一个新的context并且改变会被子组件接收。

class MediaQuery extends React.Component {
constructor(props) {
super(props);
this.state = {type:'desktop'};
} getChildContext() {
return {type: this.state.type};
} componentDidMount() {
const checkMediaQuery = () => {
const type = window.matchMedia("(min-width: 1025px)").matches ? 'desktop' : 'mobile';
if (type !== this.state.type) {
this.setState({type});
}
}; window.addEventListener('resize', checkMediaQuery);
checkMediaQuery();
} render() {
return this.props.children;
}
} MediaQuery.childContextTypes = {
type: React.PropTypes.string
};

问题在于,如果一个组件提供的context值改变了,使用那个值的子节点就不会更新如果中间的组件从shouldComponentUpdate返回了false。这样组件使用context就完全失去了控制,因此基本没有什么方法可以可靠地更新context。这个博客有一个很好地解释关于为什么这是一个问题以及你怎样避开它。

最新文章

  1. Redis学习笔记~目录
  2. 微信 5.3 for iPhone已放出 微信iphone版更新下载
  3. CentOS平台部署vsftp(基于虚拟用户)
  4. oslo.messaging 1.8.0 bug fix and blueprint
  5. php常用代码
  6. SQLServer如何处理数据集的维度变化
  7. 解决Eclipse快捷键被其他软件占用
  8. LearnMVC5-GettingStarted
  9. java8 十大新特性
  10. UVA 10561 Treblecross(博弈论)
  11. oracle解析xml(增加对9i版本的支持)
  12. Unicode 字符集及UTF-8 UTF-16编码
  13. poj3659树状DP
  14. django 学习杂记
  15. Java Swing Graphics Graphics2D的一般用法
  16. 变量类型、构造器、封装以及 LeetCode 每日一题
  17. Spring理解IOC,DI,AOP作用,概念,理解。
  18. 【Python】正则表达式纯代码极简教程
  19. Python字符串 u&quot;string&quot;,r&quot;string&quot;的写法含义
  20. 解决mysqli的中文乱码问题

热门文章

  1. Mysql安装、设置密码、编码
  2. 标签EL和JSTL解读
  3. 1.5:Unity Render Pipeline
  4. Java 新建excle文件并填充模版内容
  5. 关于springMVC的细节
  6. 原生js移除或添加样式
  7. SKCTF Writeup
  8. 证明:对于一棵二叉树,若度为2的结点有n2个,叶子结点有n0个,则n0=n2+1
  9. HttpClient throws TaskCanceledException on timeout
  10. 【HNOI 2016】序列