使用 React 的 Context API 来管理数据

1,352 阅读2分钟

Redux 之外的选择

事实上大型应用搭配 Redux 帮助管理复杂的数据流是比较好的选择, 但如果中小型应用想要摆脱 Redux 较多的概念与固定的模板语法, 我们也有新的选择: React V16 版本推出了新版的 Context API, 可以帮助我们使用较低的成本快速管理数据流.

对于 Context 的理解

Context 具有跨级提供数据的特性, 能够以一种类似总线的思想把数据全局共享. 因而对于较多需要全局共享的数据, 如果颜色主题 (Theme)、语言文案(i18n)、帐号数据(Account)、服务配置(Service Config)等, 通过 Context 来进行管理, 可以很方便是地在任意一个组件中使用共享的数据,而无需使用 localStorage 频繁读取, 或是 从根组件逐级传递到目标组件

基本 API

  • 创建数据源
// Context.js
import React from 'react';
// 初始化的数据源, 参数可以不指定, 也可以是 String|Boolean|Number|Object|Array
const Context = React.createContext('inital Data');
export { Context };
// 生成的context对象具有两个组件类对象
const { Provider, Consumer } = Context;
  • 包裹根组件
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import { Context } from './Context.js';

// 生成的数据源对象提供了 Provider 成员, 意思是数据源的提供者, value 属性的值即为[全局传递使用的数据]
// 包裹 App 根组件
ReactDOM.render(
    <Context.Provider value={'this is real inital data!'}>
        <App />
    </Context.Provider>, 
document.getElementById('root')); // 使用 Context 提供的 Provider 组件注入(提供)数据
  • 在任意组件中使用数据
import React from 'react';
import { Context } from './Context.js';
export class Page extends Component {
    render() {
        return (
            <Context.Consumer>
                {context => {
                	return context;
                }}
            </Context.Consumer> // 使用 Context 提供的 Consumer 使用(消费)数据, 最后渲染出 this is real inital data!文本节点
        );
    }
}

实战使用

  // Context.js 在 Context.js 中初始化 Context
  import React from 'react';
  const Context = React.createContext('hello mobx'); // 传入初始化的参数 'hello mobx', 可以是字符串|数字|对象
  export { Context };

  // App.js 根组件
  import React from 'react';
  import ReactDOM from 'react-dom';
  import { Context } from './Context';

  ReactDOM.render(
    <Context.Provider value={'hello redux'}>
      <RootApp />
    </Context.Provider>
  , document.getElementById('root')); // 使用 Context 提供的 Provider 注入(提供)数据

  // index.js 首页
  import React, { Component } from 'react';
  import { Context } from './Context';

  export default IndexPage extends Component {
    render() {
      return (
        <Context.Consumer>
          { context => {
            return <Span>{ context }</Span>
          }}
        </Context.Consumer> // 使用 Context 提供的 Consumer 使用(消费)数据
      )
    }
  }

使用感受

Context.Consumer 组件的写法必须写成回调函数形式, 不利于代码阅读与理解, 所有使用到数据的组件都需要手动包裹、绑定。对于现有应用,存在一定改造成本,对于中小型应用也不想加入 Redux 进行数据管理的应用, 成本较低,预期效果好