事实上大型应用搭配 Redux 帮助管理复杂的数据流是比较好的选择, 但若是中小型应用想要摆脱 Redux 较多的概念与固定的模板语法, 咱们也有新的选择: React V16 版本推出了新版的 Context API, 能够帮助咱们使用较低的成本快速管理数据流.react
Context 具备跨级提供数据的特性, 可以以一种相似总线的思想把数据全局共享. 于是对于较多须要全局共享的数据, 若是颜色主题 (Theme)、语言文案(i18n)、账号数据(Account)、服务配置(Service Config)等, 经过 Context 来进行管理, 能够很方即是地在任意一个组件中使用共享的数据,而无需使用 localStorage 频繁读取, 或是 从根组件逐级传递到目标组件redux
// 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 进行数据管理的应用, 成本较低,预期效果好dom