x-note
  • Introduction
  • JavaScript
    • JavaScript 作用域链
    • JavaScript 数据结构与类型
    • JavaScript 原型
    • JavaScript this 关键字
    • JavaScript 函数
    • JavaScript delete 运算符
    • JavaScript 内存管理与垃圾回收
    • JavaScript 严格模式与混乱模式
    • JavaScript 数字精度丢失
    • JavaScript 并发模型
    • 利用原型链实现继承
  • ECMAScript
    • ECMAScript 6 变量及常量的声明
    • ECMAScript 6 变量的解构赋值
    • ECMAScript 6 Promise 对象
    • ECMAScript 6 Symbol
    • ECMAScript 6 Proxy
    • ECMAScript 6 Reflect
    • ECMAScript 6 new.target
    • ECMAScript 6 Set 和 WeakSet
    • ECMAScript 6 Map 和 WeakMap
    • ECMAScript 6 Iterator
    • ECMAScript 6 Generator
    • ECMAScript 6 class
    • ECMAScript 7
    • ECMAScript 8 async 函数
    • ECMAScript 8 内存共享与原子性
    • ECMAScript 8 Others
    • ECMAScript 2018
    • ECMAScript 2019
  • CSS
    • CSS 块格式化上下文(BFC)
    • CSS 盒模型
    • CSS 外边距合并
    • CSS Float
    • CSS Position
    • CSS Border-Image
    • CSS BEM
    • CSS 表布局详解
    • 页面布局之单列布局
    • 页面布局之多列布局
  • React
    • React 组件的生命周期
    • React 虚拟 DOM
    • React Reconciliation
    • React Diff 算法核心
    • React Fiber
    • React Scheduling
    • React Context API
    • React Refs
    • React HMR
    • React Hook
  • VUE
    • VUE 响应式系统
    • VUE 渲染机制
    • 关于 Vue 的思考
  • Webpack
    • Webpack 基本概念
    • Webpack HMR
  • Babel
    • @babel/preset-env
  • WEB
    • WEB 基础知识及概念
      • 屏幕测量单位
      • 重绘与重排
      • 前端模块化系统
      • WEB 客户端存储
      • 浏览器的渲染过程
    • WEB 性能优化
      • WEB 性能指标
      • WEB 图片优化
      • 懒加载资源
    • WEB 安全
      • XSS
      • XSRF
      • 点击劫持
      • 同源策略(Same Origin Policy,SOP)
    • WEB 解决方案
      • webp 兼容方案
      • WEB 拖拽实现方案
    • WEB SEO
  • Git
    • Git 工作流
    • Git 内部原理
  • 传输协议
    • UDP
      • UDP 基本概念
    • TCP
      • TCP 基本概念
    • HTTP
      • HTTP 基础
      • HTTP 缓存
      • HTTP-2
      • HTTP-3
      • HTTPS
      • 自定义 HTTPS 证书
  • Protocol Buffers
    • Protocol Buffers 基础
  • gRPC
    • gRPC 简介
    • gRPC 基础概念
    • GRPC with GraphQL and TypeScript
  • 正则表达式
    • 正则表达式基础
    • 正则表达式的悲观回溯
  • 基础算法
    • 冒泡排序
    • 插入排序
    • 选择排序
    • 快速排序
    • 归并排序
    • 希尔排序
    • 堆排序
    • 桶排序
    • 计数排序
    • 基数排序
    • 二叉树的遍历
    • 动态规划
    • 回溯
  • 压缩算法
    • HPACK
    • QPACK
  • 设计模式
    • DDD
      • 模型元素的模式
    • 常见设计模式
      • 工厂方法
      • 抽象工厂
      • 构造器
      • 原型
      • 单例模式
      • 适配器模式
      • 桥接模式
      • 组合模式
      • 外观模式
      • 享元模式
      • 代理模式
      • 责任链模式
      • 命令模式
      • 迭代器模式
      • 中介者模式
      • 备忘录模式
      • 观察者模式
      • 状态模式
      • 策略模式
      • 模版方法模式
      • 访问者模式
      • 依赖注入
    • MVC
    • MVP
    • MVVM
  • 颜色空间
    • LCH
由 GitBook 提供支持
在本页
  • 旧版本的 context API 的 shouldComponentUpdate 问题
  • 旧版本 Context API Key 冲突
  • 新版本 Context API 的使用
  • 使用新版本 Context API 取代 Redux?
  • 新版 Context API 的其它问题
在GitHub上编辑
  1. React

React Context API

context 就是用来设计分享全局数据的。但是,官方并不推荐使(滥)用 context ,因为这是一个实验性的 API,在未来仍会变动,除非你打算实现一个类似于 React-Router、Redux 之类的全局组件。

旧版本的 context API 的 shouldComponentUpdate 问题

如果使用了上下文组件的父组件中shouldComponentUpdate()返回了false,则该子组件并不会更新。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class CComponent extends Component {

    static contextTypes = {
        color: PropTypes.string
    }

    render() {
        return (
            <span>{this.context.color}</span>
        );
    }
}

class MComponent extends Component {
    shouldComponentUpdate() {
        return false;
    }
    render() {
        return (
            <CComponent />
        );
    }
}

class Root extends Component {
    static childContextTypes = {
        color: PropTypes.string
    }
    getChildContext() {
        return {
            color: 'red',
        }
    }

    render() {
        return (
            <MComponent />
        );
    }
}

旧版本 Context API Key 冲突

旧版本的 Context API 中,如果子组件的 父组件 A 和父组件 B 的 Context key 相同,会产生冲突

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class CComponent extends Component {

    static contextTypes = {
        color: PropTypes.string
    }

    render() {
        return (
            <span>{this.context.color}</span>
        );
    }
}

class MComponent extends Component {
    static childContextTypes = {
        color: PropTypes.string
    }

    getChildContext() {
        return {
            color: 'blue',
        }
    }

    render() {
        return (
            <CComponent onClick={this.props.onClick} />
        );
    }
}

class Root extends Component {
    static childContextTypes = {
        color: PropTypes.string
    }

    getChildContext() {
        return {
            color: 'red',
        }
    }

    render() {
        return (
            <MComponent />
        );
    }
}

新版本 Context API 的使用

React v16.3.0 推出了新的 Context API,其中包括:

  • React.createContext(defaultValue) // 创建一个 Context 对象

  • Provider // 容器组建,类似于 Redux 的 Provider

  • Consumer // 消费组件,消费 Provider 提供的数据

import React, { Component, createContext } from 'react';

export const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};

export const ThemeContext = createContext({
  theme: themes.dark,
  toggleTheme: () => {},
});

function ThemeTogglerButton(props) {
  // The Theme Toggler Button receives not only the theme
  // but also a toggleTheme function from the context
  return (
    <ThemeContext.Consumer>
      {({theme, toggleTheme}) => (
        <button
          onClick={toggleTheme}
          style={{backgroundColor: theme.background}}>
          Toggle Theme
        </button>
      )}
    </ThemeContext.Consumer>
  );
}

// An intermediate component that uses the ThemedButton
class Toolbar extends Component {
  shouldComponentUpdate() {
    return false
  }
  render() {
    return (
      <ThemeTogglerButton onClick={this.props.changeTheme}>
        Change Theme
      </ThemeTogglerButton>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);

    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }));
    };
    this.state = {
      theme: themes.light,
      toggleTheme: this.toggleTheme,
    }
  }

  render() {
    // The entire state is passed to the provider
    return (
      <ThemeContext.Provider value={this.state}>
        <Toolbar changeTheme={this.toggleTheme} />
      </ThemeContext.Provider>
    );
  }
}

新版本的 Context API 解决了之前提到的旧版本 Context API 存在的问题。

如果组件的层级只有几层的话,不建议采用 Context

使用新版本 Context API 取代 Redux?

就目前来说,新版的 Context API 仍旧无法解决 Redux 能够解决的下问题:

  • 逻辑/数据/视图分离的代码结构

  • 在不同项目之间通用的存储和事件机制,从而允许redux-devtools这种通用的开发工具、以及类似redux-observable这种强大中间件的存在

新版 Context API 的其它问题

新版 Context API 仍存在其它值得思考的方向,由于不限制 Context 的数量,因此引发了以下几个问题。

  • 多个 Context 如何管理

  • 子组件消费多个 Context 导致的多层 Comsumer 嵌套问题

  • 子组件更新 Context 值,需要向 Provider 传递 handler,这并不符合单一职责原则

  • 子组件触发多个 Context 状态更新,导致的多次更新问题

上一页React Scheduling下一页React Refs

最后更新于6年前