文章概览
React 在版本 16.3-alpha 里引入了新的 Context API, 社区一片期待之声我们先通过简单的例子, 看下新的 Context API 长啥样, 然后再简单探讨下新的 API 的意义
文中的完整代码示例可在笔者的 GitHub 上找到, 点击传送门
看下新的 Context API
需要安装 16.3-alpha 版本的 react 构建步骤非本文重点, 可参考笔者 GitHub 上的 demo
npm install react@next react - dom@next
下面, 直接来看代码, 如果用过 react-redux 应该会觉得很眼熟
首先, 创建 context 实例:
- import React from 'react';
- import ReactDOM from 'react-dom';
- // 创建 context 实例
- const ThemeContext = React.createContext({
- background: 'red',
- color: 'white'
- });
然后, 定义 App 组件, 注意这里用到了 Provider 组件, 类似 react-redux 的 Provider 组件
- class App extends React.Component {render () {
- return (
- <ThemeContext.Provider value={{background: 'green', color: 'white'}}>
- <Header />
- </ThemeContext.Provider>
- );
- }
- }
接下来, 定义 HeaderTitle 组件注意:
Title 组件用到了 Consumer 组件, 表示要消费 Provider 传递的数据
Title 组件是 App 的孙组件, 但跳过了 Header 消费数据
- class Header extends React.Component {
- render () {
- return (
- <Title>Hello React Context API</Title>
- );
- }
- }
- class Title extends React.Component {
- render () {
- return (
- <ThemeContext.Consumer>
- {context => (
- <h1 style={{background: context.background, color: context.color}}>
- {this.props.children}
- </h1>
- )}
- </ThemeContext.Consumer>
- );
- }
- }
最后, 常规操作
- ReactDOM.render(
- <App />,
- document.getElementById('container')
- );
看下程序运行结果:
为什么有新的 Context API
用过
redux + react - redux
的同学, 应该会觉得新的 Context API 很眼熟而有看过 react-redux 源码的同学就知道, react-redux 本身就是基于旧版本的 Context API 实现的
既然已经有了现成的解决方案, 为什么还会有新的 Context API 呢?
现有 Context API 的实现存在一定问题: 比如当父组件的
shouldComponentUpdate
性能优化, 可能会导致消费了 context 数据的子组件不更新
降低复杂度: 类似 redux 全家桶这样的解决方案, 给项目引入了一定的复杂度, 尤其是对方案了解不足的同学, 遇到问题可能一筹莫展新 Context API 的引入, 一定程度上可以减少不少项目对 redux 全家桶的依赖
写在后面
新的 Context API, 个人对于性能上的提升更加期待些至于降低复杂度取代 redux 之类的, 不是我关注的重点下一步的计划就是多构造点用例来进行对比测试
更多内容, 欢迎大家关注我的公众号, 后续进行更新
相关链接
本文完整代码示例
React 新的 Context API 的 RFC
来源: https://www.cnblogs.com/chyingp/p/react-context-api.html