2018-08-08

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 定义 childContextTypesgetChildContext,React 将自动传递 context 数据子树中的组件只要定义了 contextTypes 就可以访问 context,如果没有定义 contextTypes,则 context 为 null。

  • 亲子耦合
    context 可以实现亲子之间的交互。
  • 在生命周期引用 context
    如果组件定义了 contextTypes,则生命周期的方法会新增一个参数 context。
  • 更新 context
    :当 state 和 props 发生变化时,getChildContext 会被调用,同时更新 children 。
    当中间父级 shouldComponentUpdate 返回 false,则使用该值得后代不会更新。因此没有办法可靠的更新上下文
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容