React文档(二十二)context

时间:2023-12-25 10:45:13

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。这个博客有一个很好地解释关于为什么这是一个问题以及你怎样避开它。