React16源码: React中处理LegacyContext相关的源码实现

LegacyContext

  • 老的 contextAPI 也就是我们使用 childContextTypes 这种声明方式
  • 来从父节点为它的子树提供 context 内容的这么一种方式
  • 遗留的contextAPI 在 react 17 被彻底移除了,就无法使用了
  • 那么为什么要彻底移除这个contextAPI的使用方式呢?
  • 因为它对性能的影响会比较的大,它会影响整个子树的一个更新过程
  • 它嵌套的context提供者是需要进行一个数据的合并的
    • 嵌套组件中,如果父子两者都提供相同的变量,会进行一个合并
    • 越接近里层,越会被选择
    • 也就是说在孙子消费变量的时候,选择父亲的,舍弃爷爷的

2 )源码

定位到 packages/react-reconciler/src/ReactFiberBeginWork.js#L1522

在这里,有这个判断 if ( oldProps === newProps && !hasLegacyContextChanged() && updateExpirationTime < renderExpirationTime ) {}

看到有

import {hasContextChanged as hasLegacyContextChanged
} from './ReactFiberContext';

关注 hasLegacyContextChanged 基于此,定位到 (packages/react-reconciler/src/ReactFiberContext.js#L115)[https://github.com/facebook/react/blob/v16.6.3/packages/react-reconciler/src/ReactFiberContext.js#L115]

// 要去推入 stack 的值的时候,就要去创建这么一个 cursor 来标记不同类型的一个值
function hasContextChanged(): boolean {return didPerformWorkStackCursor.current;
}

回顾到 context-stack 中

// packages/react-reconciler/src/ReactFiberContext.js#L36// A cursor to the current merged context object on the stack.
// 用来记录我们当前的我们更新到某一个节点之后,它应该可以拿到的context对应的所有值
let contextStackCursor: StackCursor<Object> = createCursor(emptyContextObject);// A cursor to a boolean indicating whether the context has changed.
// 代表着我们在更新到某一个节点的时候,它这个context是否有变化这么一个情况
let didPerformWorkStackCursor: StackCursor<boolean> = createCursor(false);

再次回到 ReactFiberBeginWork.js 中的 if ( oldProps === newProps && !hasLegacyContextChanged() && updateExpirationTime < renderExpirationTime ) {}

对于在 beginWork 中的 context 操作,可以看上述判断成立的条件下的代码,即便有符合跳过更新的操作,依然 需要 push 和 pop 操作

进入代码

switch (workInProgress.tag) {case ClassComponent: {const Component = workInProgress.type;// 如果当前组件是一个 provider 则进行 push 操作if (isLegacyContextProvider(Component)) {pushLegacyContextProvider(workInProgress);}break;}
}
  • 跟遗留的 contextAPI 有关,通过 legency 标志,如果一个组件能够作为一个 context 的提供者

  • 那么它肯定是一个 ClassComponent, 因为要通过 getchildcontext 这么一个方法来声明我们子树当中提供了哪些 concontext

  • 最主要的就是来看在classcomponent的更新过程当中,如果它是一个contextprovider,那么它要执行的操作是 pushLegacyContextProvider

  • 进入 isLegacyContextProvider, 看到它是 isContextProvider 的别名

    // 这个 type 就是组件实例,这个 childContextTypes
    function isContextProvider(type: Function): boolean {// 通过判断应用中声明的 class 上面是否有这个属性const childContextTypes = type.childContextTypes;return childContextTypes !== null && childContextTypes !== undefined;
    }
    
    • 通过声明的这个class给它挂载 childContextTypes 来表示它是一个context的提供者
    • 只有声明了这个之后,它才会作为一个context的provider来提供子树上面的context
    • 如果不这么声明,即便在class里面提供了 getChildContext 这个方法,还是拿不到对应的context
  • 进入 pushLegacyContextProvider 它是 pushContextProvider 的别名

    function pushContextProvider(workInProgress: Fiber): boolean {const instance = workInProgress.stateNode;// We push the context as early as possible to ensure stack integrity.// If the instance does not exist yet, we will push null at first,// and replace it on the stack later when invalidating the context.const memoizedMergedChildContext =(instance && instance.__reactInternalMemoizedMergedChildContext) ||emptyContextObject;// Remember the parent context so we can merge with it later.// Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.previousContext = contextStackCursor.current; // 获取之前的 context 挂载到全局变量上push(contextStackCursor, memoizedMergedChildContext, workInProgress);push(didPerformWorkStackCursor,didPerformWorkStackCursor.current,workInProgress,);return true;
    }
    

以上是可以跳出当前组件的更新的一个处理情况

如果我们可以跳出组件的更新,也就是代表着当前这个 classComponent,它的state它的props都应该是没有任何变化的

这个时候, 当然是可以直接使用保存在它上面原始的 context 的对象

如果它是一个需要更新的 classComponent,需要看一下 updateClassComponent 这个更新方法

function updateClassComponent(current: Fiber | null,workInProgress: Fiber,Component: any,nextProps,renderExpirationTime: ExpirationTime,
) {// Push context providers early to prevent context stack mismatches.// During mounting we don't know the child context yet as the instance doesn't exist.// We will invalidate the child context in finishClassComponent() right after rendering.let hasContext;if (isLegacyContextProvider(Component)) {hasContext = true;pushLegacyContextProvider(workInProgress);} else {hasContext = false;}prepareToReadContext(workInProgress, renderExpirationTime);const instance = workInProgress.stateNode;let shouldUpdate;if (instance === null) {if (current !== null) {// An class component without an instance only mounts if it suspended// inside a non- concurrent tree, in an inconsistent state. We want to// tree it like a new mount, even though an empty version of it already// committed. Disconnect the alternate pointers.current.alternate = null;workInProgress.alternate = null;// Since this is conceptually a new fiber, schedule a Placement effectworkInProgress.effectTag |= Placement;}// In the initial pass we might need to construct the instance.constructClassInstance(workInProgress,Component,nextProps,renderExpirationTime,);mountClassInstance(workInProgress,Component,nextProps,renderExpirationTime,);shouldUpdate = true;} else if (current === null) {// In a resume, we'll already have an instance we can reuse.shouldUpdate = resumeMountClassInstance(workInProgress,Component,nextProps,renderExpirationTime,);} else {shouldUpdate = updateClassInstance(current,workInProgress,Component,nextProps,renderExpirationTime,);}return finishClassComponent(current,workInProgress,Component,shouldUpdate,hasContext,renderExpirationTime,);
}
  • 一进来就调用了 isLegacyContextProvider 方法

    • 就是如果它是一个contextprovider,那么它要进行 push 操作 pushLegacyContextProvider
  • 接下去, 它调用了一个方法,叫做 prepareToReadContext 这么一个方法

    • 这个方法和新的contextAPI有关,先跳过
  • 接下去基本上没有跟 context 相关的内容了,这里进入 finishClassComponent

    function finishClassComponent(current: Fiber | null,workInProgress: Fiber,Component: any,shouldUpdate: boolean,hasContext: boolean,renderExpirationTime: ExpirationTime,
    ) {// Refs should update even if shouldComponentUpdate returns falsemarkRef(current, workInProgress);const didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;if (!shouldUpdate && !didCaptureError) {// Context providers should defer to sCU for renderingif (hasContext) {invalidateContextProvider(workInProgress, Component, false);}return bailoutOnAlreadyFinishedWork(current,workInProgress,renderExpirationTime,);}const instance = workInProgress.stateNode;// RerenderReactCurrentOwner.current = workInProgress;let nextChildren;if (didCaptureError &&typeof Component.getDerivedStateFromError !== 'function') {// If we captured an error, but getDerivedStateFrom catch is not defined,// unmount all the children. componentDidCatch will schedule an update to// re-render a fallback. This is temporary until we migrate everyone to// the new API.// TODO: Warn in a future release.nextChildren = null;if (enableProfilerTimer) {stopProfilerTimerIfRunning(workInProgress);}} else {if (__DEV__) {ReactCurrentFiber.setCurrentPhase('render');nextChildren = instance.render();if (debugRenderPhaseSideEffects ||(debugRenderPhaseSideEffectsForStrictMode &&workInProgress.mode & StrictMode)) {instance.render();}ReactCurrentFiber.setCurrentPhase(null);} else {nextChildren = instance.render();}}// React DevTools reads this flag.workInProgress.effectTag |= PerformedWork;if (current !== null && didCaptureError) {// If we're recovering from an error, reconcile without reusing any of// the existing children. Conceptually, the normal children and the children// that are shown on error are two different sets, so we shouldn't reuse// normal children even if their identities match.forceUnmountCurrentAndReconcile(current,workInProgress,nextChildren,renderExpirationTime,);} else {reconcileChildren(current,workInProgress,nextChildren,renderExpirationTime,);}// Memoize state using the values we just used to render.// TODO: Restructure so we never read values from the instance.workInProgress.memoizedState = instance.state;// The context might have changed so we need to recalculate it.if (hasContext) {invalidateContextProvider(workInProgress, Component, true);}return workInProgress.child;
    }
    
    • hasContext 是否是一个 contextProvider
    • 如果是 true, 则执行 invalidateContextProvider(workInProgress, Component, false);
      function invalidateContextProvider(workInProgress: Fiber,type: any,didChange: boolean,
      ): void {const instance = workInProgress.stateNode;invariant(instance,'Expected to have an instance by this point. ' +'This error is likely caused by a bug in React. Please file an issue.',);// 如果有变化if (didChange) {// Merge parent and own context.// Skip this if we're not updating due to sCU.// This avoids unnecessarily recomputing memoized values.const mergedContext = processChildContext(workInProgress,type,previousContext,);instance.__reactInternalMemoizedMergedChildContext = mergedContext;// Replace the old (or empty) context with the new one.// It is important to unwind the context in the reverse order.pop(didPerformWorkStackCursor, workInProgress);pop(contextStackCursor, workInProgress);// Now push the new context and mark that it has changed.push(contextStackCursor, mergedContext, workInProgress);push(didPerformWorkStackCursor, didChange, workInProgress);} else {pop(didPerformWorkStackCursor, workInProgress);push(didPerformWorkStackCursor, didChange, workInProgress);}
      }
      
      • 通过 processChildContext 计算出新的 context 并挂载到 __reactInternalMemoizedMergedChildContext
      • 之后,pop 2次,push 2次 来处理了栈内的顺序
      • 进入 processChildContext 看下这个方法
        function processChildContext(fiber: Fiber,type: any,parentContext: Object,
        ): Object {const instance = fiber.stateNode;const childContextTypes = type.childContextTypes;// TODO (bvaughn) Replace this behavior with an invariant() in the future.// It has only been added in Fiber to match the (unintentional) behavior in Stack.// 这个属性一定是 function 才能生效if (typeof instance.getChildContext !== 'function') {if (__DEV__) {const componentName = getComponentName(type) || 'Unknown';if (!warnedAboutMissingGetChildContext[componentName]) {warnedAboutMissingGetChildContext[componentName] = true;warningWithoutStack(false,'%s.childContextTypes is specified but there is no getChildContext() method ' +'on the instance. You can either define getChildContext() on %s or remove ' +'childContextTypes from it.',componentName,componentName,);}}return parentContext;}let childContext;if (__DEV__) {ReactCurrentFiber.setCurrentPhase('getChildContext');}startPhaseTimer(fiber, 'getChildContext');childContext = instance.getChildContext(); // 执行这个 提供的api, 获取数据stopPhaseTimer();if (__DEV__) {ReactCurrentFiber.setCurrentPhase(null);}for (let contextKey in childContext) {invariant(contextKey in childContextTypes,'%s.getChildContext(): key "%s" is not defined in childContextTypes.',getComponentName(type) || 'Unknown',contextKey,);}// 忽略if (__DEV__) {const name = getComponentName(type) || 'Unknown';checkPropTypes(childContextTypes,childContext,'child context',name,// In practice, there is one case in which we won't get a stack. It's when// somebody calls unstable_renderSubtreeIntoContainer() and we process// context from the parent component instance. The stack will be missing// because it's outside of the reconciliation, and so the pointer has not// been set. This is rare and doesn't matter. We'll also remove that API.ReactCurrentFiber.getCurrentFiberStackInDev,);}// 最终是两者 mergereturn {...parentContext, ...childContext};
        }
        
        • 其实,这个 processChildContext 非常简单,获取 context,合并 context
        • 这里的 parentContext 是传入的 previousContext, 这个是上面调用 pushContextProvider 时设置的全局变量 contextStackCursor.current
        • 也就是 父组件中 提供的 context 对象,最终都是为了合并
  • 总结来说,父子孙三个组件,在更新子组件的时候,先去push了一个它之前存在的这个属性

  • 因为我们不知道这个组件它是否要更新,不管它是否要更新,都要先都要执行 push 的一个操作

  • 所以,先 push 一个老的值进去再说, 然后到后面,如果发现这个组件它是要更新的,就调用这个 invalidateContextProvider 方法

  • 调用了这个方法之后, 根据传进来的 didChange,如果是 true 表示要更新,要重新去计算一个新的合并过的这个context, 即 mergedContext 给它推入到栈里面

  • 对于子组件来说,它的所有子树所获取到的context肯定是经过子组件,和上层的父组件合并的 context 了, 也就是 contextStackCursor 这里

  • 同时对于 didPerformWorkStackCursor 来说,因为 didChange 是 true,它的 current 肯定也是 true

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/654524.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Date类型转成字符类型(String),字符类型(String)转成Date类型

效果图 注意&#xff1a;不建议使用YYYY-MM-dd HH:mm:ss格式&#xff0c;使用yyyy-MM-dd HH:mm:ss格式 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;public class DateTimeDemo {public static void main(String[] args) thro…

群辉开启WebDav服务+cpolar内网穿透实现移动端ES文件浏览器远程访问本地NAS文件

文章目录 1. 安装启用WebDAV2. 安装cpolar3. 配置公网访问地址4. 公网测试连接5. 固定连接公网地址6. 使用固定地址测试连接 本文主要介绍如何在群辉中开启WebDav服务&#xff0c;并结合cpolar内网穿透工具生成的公网地址&#xff0c;通过移动客户端ES文件浏览器即可实现移动设…

在Compose中控制组件中数据的流速

文章目录 一、场景描述二、代码示例 一、场景描述 在Compose中设计思想是分为状态和组件的&#xff0c;组件由状态控制。这个操作和传统的AndroidView不太一样。在Compose中对话框Dialog也是一个组件&#xff0c;其显示和隐藏由外部状态控制。这里有一个场景&#xff0c;假设显…

【C语言】(7)输入输出

输出 printf printf 是 C 语言中最常用的输出函数。它可以将格式化的字符串输出到控制台。 基本语法&#xff1a; int printf(const char *format, ...);format 是格式化字符串&#xff0c;用于指定输出的格式。... 表示可变数量的参数&#xff0c;根据格式化字符串输出相应…

ECS120fundamentals of compiling

Auto-gradedproblemsTheseproblemsarenotrandomized,sothereisnoneedtofirstsubmitafilenamedreq.Eachproblembelowappearsasaseparate“Assignment”inGradescope,beginningwith“HW1:”.1.1DFAsForeachproblem submittoGradescopea.dfafiledescribinga DFA deciding thegiven…

电路笔记 :MOS场效应晶体管+红外遥控+AMS1117 电源模块

三极管&#xff08;BJT&#xff0c;Bipolar Junction Transistor&#xff09;和 MOSFET&#xff08;Metal-Oxide-Semiconductor Field-Effect Transistor&#xff09;是两种不同类型的晶体管&#xff0c;它们在工作原理、性能特性和应用方面有一些重要的区别。 结构和工作原理…

大模型学习笔记一:大模型应开发基础(模型归类选型、安全因素选型、)

文章目录 一、大模型一些概念介绍二、市面上大模型对比三、大模型使用安全选型四、使用大模型的方式&#xff08;一问一答、Agent Function Calling、RAG、Fine-tuning五、大模型使用路线九、补充说明1&#xff09;注意力机制讲解 一、大模型一些概念介绍 1&#xff09;产品和大…

时序预测 | Python基于Multihead-Attention-TCN-LSTM的时间序列预测

目录 效果一览基本介绍程序设计参考资料 效果一览 基本介绍 时序预测 | Python基于Multihead-Attention-TCN-LSTM的时间序列预测 Multihead-Attention-TCN-LSTM&#xff08;多头注意力-TCN-LSTM&#xff09;是一种结合了多个注意力机制、时序卷积网络&#xff08;TCN&#xff0…

Flutter pubspec.yaml添加三方库、插件依赖时版本号前面的^作用

在 Flutter 的 pubspec.yaml文件中&#xff0c;依赖的版本号前面的 ^符号用于指定版本范围&#xff0c;而没有 ^ 符号则表示精确指定版本 带 ^ 符号 在依赖版本前使用 ^ 符号&#xff0c;代表接受这个依赖的任何向上兼容的版本&#xff08;主版本号相同&#xff0c;次版本号或…

Windows下EDK2快速搭建(详细)过程总结附软件包地址

目录 简介一、软件包下载安装VS2019下载NASM安下载LLVM/CLANG下载IASL下载安装Python安装OpenSSL下载EDK2 二、设置环境变量新增python系统变量新增NASM系统变量 三、编译3.1 在edk2目录直接输入cmd3.2 在cmd目录输入&#xff1a;edksetup.bat3.3 打开edk2编译窗口3.4 确认编译…

代码随想录算法训练营第四天-链表part2

day2和day3回家太晚&#xff0c;刷完题忘记写笔记了 - -&#xff01; 24.两两交换链表中的节点 给自己的笔记&#xff1a; 虚拟节点法是创建一个节点&#xff0c;它的next指针指向链表的头节点&#xff0c;这样便于&#xff1a; current指向虚拟节点&#xff0c;然后对链表进…

STL相关介绍及具体应用

STL的诞生 C的面向对象和泛型编程的思想目的就是提升代码复用性。为了建立数据结构和算法的一套标准&#xff0c;且避免重复无意义的代码工作&#xff0c;诞生了STL STL基本概念 1、STL&#xff08;Standard Template Library&#xff09;称为标准模板库 2、STL从广义上分为…

awk命令使用方法

简介 awk 是一种强大的文本处理工具&#xff0c;可以用于处理结构化的文本数据。它可以根据指定的模式和动作来筛选、处理和格式化文本。 下面是一些常见的 awk 命令使用方法。 详细介绍 基本语法&#xff1a; awk pattern { action } filename其中&#xff0c;pattern 是用…

微软 Power Apps Canvas App 画布应用将上传的附件转化为base64编码操作

微软 Power Apps Canvas App 画布应用将上传的附件结合Power Automate转化为base64编码操作 在使用canvas app的过程中&#xff0c;我们有时需要将上传的文件转换为base64存入数据库或者&#xff0c;调用外部接口传参&#xff0c;那么看下如何将文件转化为base64编码格式。 首先…

【数据分析】numpy基础第三天

前言 本文只会讲解最常用的加、减、乘、除&#xff0c;点乘&#xff08;或叫矩阵乘法&#xff09;、还有广播机制。 本文代码 链接提取码&#xff1a;1024 第1部分&#xff1a;基础数学计算 使用NumPy进行基本的数学运算是十分直观和简单的。下面我们将展示一些基本的加、…

笨蛋总结JVM

笨蛋总结JVM 由于Java语言将自己的内存控制权交给了虚拟机&#xff0c;所以需要了解虚拟机的运行机制 &#xff08;主要用于回顾JVM&#xff09; 笨蛋总结JVM 笨蛋总结JVM1.运行时数据区域线程私有区域程序计数器Java虚拟机栈本地方法栈 线程共享区域堆方法区 1.2程序计数器…

SQL编程作业

题目&#xff1a; 创建职工表以及职工工资表 职工表字段&#xff1a;工号&#xff0c;姓名&#xff0c;性别&#xff0c;年龄 工资表字段&#xff1a;编号自增&#xff0c;职工工号&#xff0c;基础工资10000 通过触发器实现&#xff1a; 对职工进行添加时 工资表中也要体现当…

键盘上Ins键的作用

前几天编写文档时&#xff0c;发现一个问题&#xff1a;插入内容时&#xff0c;输入的字符将会覆盖光标位置后的字符。原来是按到了键盘上的 Ins键&#xff0c;解决方法是&#xff1a;再按一次 Ins键&#xff08;Ins键如果独立作为一键时&#xff0c;否则使用 “Fn Ins”组合键…

PHP雪花算法

雪花算法&#xff08;Snowflake Algorithm&#xff09;是一种分布式唯一ID生成算法&#xff0c;旨在满足分布式系统中对唯一标识的需求。它由Twitter公司的工程师Snowman&#xff08;Snowflake的创造者&#xff09;设计&#xff0c;用于生成全局唯一的ID&#xff0c;以应对分布…

并查集的学习

并查集可以理解为数学上的集合 并查集一般以树这种数据结构来储存每一个元素&#xff0c;判断两个元素是否为同一个集合&#xff0c;通常判断两个元素所在的树的根结点是否相同&#xff0c;因为比较两个元素是否是同一个树要向上查找根结点&#xff0c;所以一般用双亲表示法&a…