React 高级指南
React 新版上下文(context)
- context ?
答
:上下文(Context) 提供了一种通过组件树
传递数据的方法,无需在每个级别手动传递 props 属性
。上下文(Context) 提供了在组件之间共享
这些值的方法,而不必在树的每个层级显式
传递一个 prop 。
- 何时使用 context?
答
:context 旨在一个组件树
种共享一个全局
的数据。可以避免通过中间元素传递props。
- React.createContext ?
答
:
const {Provider, Consumer} = React.createContext(defaultValue)
创建一个 {Provider, Consumer}
对,当 React 渲染 Consumer 组件
时,会在组件树
中查找最近的 Provider
获取 context 值
。
defaultValue
,当 Consumer 在组件树中没有找到匹配的 Provider 时,使用 defaultValue。即使 Provider 赋值为 undefined
,Consumer 不会使用 defaultValue。
- Provider ?
答
:
<Provider value={/* some value */}>
Provider 提供 value 给 Consumer。
- Consumer ?
答
:
<Consumer>
{value => /* 基于 context value 渲染 something */}
</Consumer>
接收一个函数作为子节点
,该函数的参数为 context value,返回一个 React 节点。
note
:当 Provider value 值发生变化时,所有对应该 Provider 的 Consumer 都会重新渲染。
从 Provider 到 Consumer 的传播不受 shouldComponentUpdate 的方法约束。即使父组件不更新了,Consumer 也会更新。
- 从嵌套组件中更新 context ?
答
:我们通常需要从组件树的嵌套组件中更新 context。为了解决这个问题,我们可以在 context 定义一个函数
,以允许Consumer更新 context
。
- 如何使用多个 context ?
答
:React 要求每个 context Consumer 都为树中一个单独的节点。
如果经常使用两个或多个 context,我们可以考虑创建一个渲染属性组件
,包括多个 context。
React 旧版上下文
- 如何使用 context 呢?
答
:
import PropTypes from 'prop-types';
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: 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: PropTypes.string
};
context Provider 定义 childContextTypes
和 getChildContext
,React 将自动传递 context 数据
。子树
中的组件
只要定义了 contextTypes
就可以访问 context,如果没有定义 contextTypes,则 context 为 null。
- 亲子耦合
context 可以实现亲子之间的交互。
- 在生命周期引用 context
如果组件定义了 contextTypes,则生命周期的方法会新增一个参数 context。
- 更新 context
答
:当 state 和 props 发生变化时,getChildContext 会被调用,同时更新 children 。
当中间父级shouldComponentUpdate
返回 false,则使用该值得后代不会更新。因此没有办法可靠的更新上下文
。