需要安装16.3-alpha版本的react。构建步骤非本文重点,本文主要和大家分享react 16.3之context api详解,希望能帮助到大家。
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> ); } }
接下来,定义header、title组件。注意:
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 16.3之context api详解的详细内容。
