React的React.createContext()源码解析(四)
一.产生context原因
二.context的两种实现方式
1.老版本(React16.x前)
//根组件
class MessageList extends React.Component {
//getChildContext函数,返回一个context对象
getChildContext() {
return { color: 'purple', text: 'item text' }
}
render() {
return (
<div>
<Message text="this is MessageList" />
</div>
)
}
}
//指定context结构类型 如果不写 产生错误
//import T from 'prop-types';
MessageList.childContextTypes = {
color: T.string,
text: T.string,
}
//中间组件
class Message extends React.Component {
render() {
return (
<div>
<MessageItem />
</div>
)
}
}
//孙子组件(接收组件)
class MessageItem extends React.Component {
render() {
//this.context获取上下文
return (
<div>
{this.context.text}
</div>
)
}
}
//孙子组件声明 接收context结构类型 如果contextTypes没有定义 context将是一个空对象
MessageItem.contextTypes = {
text: T.string
}
为什么会被摒弃?
2.新版本(React16.x后)
//创建两个组件 Provider,Consumer
//let {Provider,Consumer}=React.createContext(defaultValue); //defaultValue可以设置共享的默认数据 当Provider不存在的时候 defaultValue生效
const { Provider, Consumer } = React.createContext({ theme: "green" }) // 这里MessageList render(){<Content />}
class MessageList extends React.Component {
render() {
//Procider组件遍历子组件,并且有一个属性value,且value相当于旧版本的getChildContext()的返回的context对象 用来提供数据
return (
<Provider value={{ theme: "pink" }}>
<Content />
</Provider>
)
}
}
//中间组件
function Content() {
return (
<div>
<Button />
</div>
)
}
//接收组件,如果子组件是Consumer的话,将value作为参数值,传递给新创建的Consumer,渲染一个函数组件
function Button() {
return (
<Consumer>
{({ theme }) => (
<button
style={{ backgroundColor: theme }}>
Toggle Theme
</button>
)}
</Consumer>
)
}
注意:将undefined
传递给<Provider>
的value
时,createContext
中的defaultValue
不会生效,Consumer
的value
显示空值
三,React.createContext()源码解析
//calculateChangedBits方法,使用Object.is()计算新老context的一个变化
function createContext(defaultValue, calculateChangedBits) {
if (calculateChangedBits === undefined) {
calculateChangedBits = null;
} else {
{
!(calculateChangedBits === null || typeof calculateChangedBits === 'function') ? warningWithoutStack$1(false, 'createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits) : void 0;
}
} var context = {
//context的$$typeof在createElement中的type对象中存储的
$$typeof: REACT_CONTEXT_TYPE,
//作为支持多个并发渲染器的解决方法 我们将一些渲染器作为主要渲染器 其他渲染器为辅助渲染器
_calculateChangedBits: calculateChangedBits,
//我们希望有两个并发渲染器:主要和次要
//辅助渲染器将自己的context的value存储在单独的字段里
//_currentValue和_currentValue2作用一样,只是作用平台不同
_currentValue: defaultValue, //Provider的value属性
_currentValue2: defaultValue,
//用来追踪context的并发渲染器的数量
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
}; //context.Provider的_context指向context对象
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false; {
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context,
_calculateChangedBits: context._calculateChangedBits
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
warning$1(false, 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
} return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
warning$1(false, 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
} return context.Consumer;
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer;
} {
context._currentRenderer = null;
context._currentRenderer2 = null;
}
//返回一个context对象
return context;
}
返回的context内容:
React的React.createContext()源码解析(四)的更多相关文章
- Mybatis源码解析(四) —— SqlSession是如何实现数据库操作的?
Mybatis源码解析(四) -- SqlSession是如何实现数据库操作的? 如果拿一次数据库请求操作做比喻,那么前面3篇文章就是在做请求准备,真正执行操作的是本篇文章要讲述的内容.正如标题一 ...
- Sentinel源码解析四(流控策略和流控效果)
引言 在分析Sentinel的上一篇文章中,我们知道了它是基于滑动窗口做的流量统计,那么在当我们能够根据流量统计算法拿到流量的实时数据后,下一步要做的事情自然就是基于这些数据做流控.在介绍Sentin ...
- React的Component,PureComponent源码解析(二)
1.什么是Component,PureComponent? 都是class方式定义的基类,两者没有什么大的区别,只是PureComponent内部使用shouldComponentUpdate(nex ...
- Dubbo 源码解析四 —— 负载均衡LoadBalance
欢迎来我的 Star Followers 后期后继续更新Dubbo别的文章 Dubbo 源码分析系列之一环境搭建 Dubbo 入门之二 --- 项目结构解析 Dubbo 源码分析系列之三 -- 架构原 ...
- iOS即时通讯之CocoaAsyncSocket源码解析四
原文 前言: 本文为CocoaAsyncSocket源码系列中第二篇:Read篇,将重点涉及该框架是如何利用缓冲区对数据进行读取.以及各种情况下的数据包处理,其中还包括普通的.和基于TLS的不同读取操 ...
- AFNetworking2.0源码解析<四>
结构 AFURLResponseSerialization负责解析网络返回数据,检查数据是否合法,把NSData数据转成相应的对象,内置的转换器有json,xml,plist,image,用户可以很方 ...
- Celery 源码解析四: 定时任务的实现
在系列中的第二篇我们已经看过了 Celery 中的执行引擎是如何执行任务的,并且在第三篇中也介绍了任务的对象,但是,目前我们看到的都是被动的任务执行,也就是说目前执行的任务都是第三方调用发送过来的.可 ...
- vuex 源码解析(四) mutation 详解
mutation是更改Vuex的store中的状态的唯一方法,mutation类似于事件注册,每个mutation都可以带两个参数,如下: state ;当前命名空间对应的state payload ...
- MyBatis 3源码解析(四)
四.MyBatis 查询实现 Employee empById = mapper.getEmpById(1); 首先会调用MapperProxy的invoke方法 @Override public O ...
随机推荐
- django学习 session保持登录,且登出
学一点记一点 刚刚进来的时候突然发现,博客园的主页在缩小的时候会发生一些挤压,有点意思 今天刚看了session,感觉之前太迷茫,把问题想得过于复杂了. 我这个是建立在有登录和注册的功能上的演示. 首 ...
- rest_framework:url控制
一.基本路由(原始方式) 二.半自动路由(视图继承ModelViewSet) 三.自动路由(自动生成路由) 准备工作: models中创建一张表,默认使用sqlite数据库,更新表 新增测试数据 加载 ...
- VAR模型学习笔记
目录 1 定义 VAR模型的具体步骤 建模步骤及公式 代码实现 1 定义 VAR模型除了分析自身滞后项的影响外,还分析其他相关因素的滞后项对未来值产生的影响参考 用来分析随机扰动对系统的动态冲击的大小 ...
- Python入门6 —— 流程控制 - if判断
代码块: 1.代码块指的是同一级别的代码,在python中用缩进相同的空格数(除了顶级代码块无任何缩进之外,其余代码块都是在原有的基础上缩进4个空格)来标识同一级的代码块 2.同一级别的代码块会按照自 ...
- 15分钟带你了解前端工程师必知的javascript设计模式(附详细思维导图和源码)
15分钟带你了解前端工程师必知的javascript设计模式(附详细思维导图和源码) 前言 设计模式是一个程序员进阶高级的必备技巧,也是评判一个工程师工作经验和能力的试金石.设计模式是程序员多年工作经 ...
- hashmap与currentHashMap
hashmap的缺点 多线程不安全,在并发场景下使用时容易出现死循环,脏读问题等 死循环:https://juejin.im/post/5a66a08d5188253dc3321da0 (这篇好点)h ...
- 获取 Android APP 版本信息工具类(转载)
获取 Android APP 版本信息工具类 获取手机APP版本信息工具类 1.获取版本名称 2.获取版本号 3.获取App的名称 package com.mingyue.nanshuibeidiao ...
- Redis 要学的
https://www.cnblogs.com/kismetv/p/8654978.html#t21 各个类型底层原理 慢查询 pipeline BitMaps 发布订阅 主从复制 psync psy ...
- python 3.8 下安装 tensorflow 1.14
pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.14.0-py3-none-a ...
- tensorflow学习笔记——GoogLeNet
GoogLeNet是谷歌(Google)研究出来的深度网络结构,为什么不叫“GoogleNet”,而叫“GoogLeNet”,据说是为了向“LeNet”致敬,因此取名为“GoogLeNet”,所以我们 ...