React16源码: React中的updateHostComponent的源码实现

updateHostComponent


1 )概述

  • completeWork 阶段的 HostComponent 处理,继续前文所述
  • 在更新的逻辑里面,调用了 updateHostComponent
  • 进行前后props对应的dom的attributes变化的对比情况
  • 这个方法也是根据不同环境来定义的,我们这里只专注于 react-dom 环境

2 )源码

定位到 packages/react-reconciler/src/ReactFiberCompleteWork.js#L586

这里是 updateHostComponent 调用的地方

updateHostComponent(current,workInProgress,type,newProps,rootContainerInstance,
);if (current.ref !== workInProgress.ref) {markRef(workInProgress);
}

接着,进入其定义

updateHostComponent = function(current: Fiber,workInProgress: Fiber,type: Type,newProps: Props,rootContainerInstance: Container,
) {// If we have an alternate, that means this is an update and we need to// schedule a side-effect to do the updates.const oldProps = current.memoizedProps;// 全等对象,没有变化过,直接 returnif (oldProps === newProps) {// In mutation mode, this is sufficient for a bailout because// we won't touch this node even if children changed.return;}// If we get updated because one of our children updated, we don't// have newProps so we'll have to reuse them.// TODO: Split the update API as separate for the props vs. children.// Even better would be if children weren't special cased at all tho.// 获取 dom 和 contextconst instance: Instance = workInProgress.stateNode;const currentHostContext = getHostContext();// TODO: Experiencing an error where oldProps is null. Suggests a host// component is hitting the resume path. Figure out why. Possibly// related to `hidden`.// 注意这里,const updatePayload = prepareUpdate(instance,type,oldProps,newProps,rootContainerInstance,currentHostContext,);// TODO: Type this specific to this type of component.workInProgress.updateQueue = (updatePayload: any);// If the update payload indicates that there is a change or if there// is a new ref we mark this as an update. All the work is done in commitWork.if (updatePayload) {markUpdate(workInProgress);}
};
  • 进入 prepareUpdate
    // 忽略 DEV 判断,这里直接 return 了 diffProperties 的调用
    export function prepareUpdate(domElement: Instance,type: string,oldProps: Props,newProps: Props,rootContainerInstance: Container,hostContext: HostContext,
    ): null | Array<mixed> {if (__DEV__) {const hostContextDev = ((hostContext: any): HostContextDev);if (typeof newProps.children !== typeof oldProps.children &&(typeof newProps.children === 'string' ||typeof newProps.children === 'number')) {const string = '' + newProps.children;const ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo,type,);validateDOMNesting(null, string, ownAncestorInfo);}}return diffProperties(domElement,type,oldProps,newProps,rootContainerInstance,);
    }
    
    • 进入 diffProperties
      // 这个方法和前文中的 setInitialProperties 有一定的类似, 根据不同的节点做不同的操作
      // Calculate the diff between the two objects.
      export function diffProperties(domElement: Element,tag: string,lastRawProps: Object,nextRawProps: Object,rootContainerElement: Element | Document,
      ): null | Array<mixed> {if (__DEV__) {validatePropertiesInDevelopment(tag, nextRawProps);}let updatePayload: null | Array<any> = null;let lastProps: Object;let nextProps: Object;switch (tag) {case 'input':lastProps = ReactDOMInput.getHostProps(domElement, lastRawProps);nextProps = ReactDOMInput.getHostProps(domElement, nextRawProps);updatePayload = [];break;case 'option':lastProps = ReactDOMOption.getHostProps(domElement, lastRawProps);nextProps = ReactDOMOption.getHostProps(domElement, nextRawProps);updatePayload = [];break;case 'select':lastProps = ReactDOMSelect.getHostProps(domElement, lastRawProps);nextProps = ReactDOMSelect.getHostProps(domElement, nextRawProps);updatePayload = [];break;case 'textarea':lastProps = ReactDOMTextarea.getHostProps(domElement, lastRawProps);nextProps = ReactDOMTextarea.getHostProps(domElement, nextRawProps);updatePayload = [];break;default:lastProps = lastRawProps;nextProps = nextRawProps;if (typeof lastProps.onClick !== 'function' &&typeof nextProps.onClick === 'function') {// TODO: This cast may not be sound for SVG, MathML or custom elements.trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));}break;}assertValidProps(tag, nextProps);let propKey;let styleName;let styleUpdates = null;// 那么接下去会有两个循环// 第一个循环是循环 lastProps, 就是上一次渲染的结果产生的props// 这是第一次大循环: 找到在旧的props上有的属性,在新的props上没有的,也就是找到前后对比中删除的propsfor (propKey in lastProps) {// 对 新旧 props 进行循环判断: 新props有key 或 旧props没有key 或 旧props为null 则跳过此keyif (nextProps.hasOwnProperty(propKey) ||!lastProps.hasOwnProperty(propKey) ||lastProps[propKey] == null) {// 符合这个条件,不是被删除的属性,不会加到最后的 updatePayloadcontinue;}// 对符合被删除属性来说,进行删除 style 的操作if (propKey === STYLE) {const lastStyle = lastProps[propKey];for (styleName in lastStyle) {if (lastStyle.hasOwnProperty(styleName)) {if (!styleUpdates) {styleUpdates = {};}styleUpdates[styleName] = '';}}// 后面的其他判断,都没有做什么事情,可以跳过了} else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {// Noop. This is handled by the clear text mechanism.} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||propKey === SUPPRESS_HYDRATION_WARNING) {// Noop} else if (propKey === AUTOFOCUS) {// Noop. It doesn't work on updates anyway.} else if (registrationNameModules.hasOwnProperty(propKey)) {// This is a special case. If any listener updates we need to ensure// that the "current" fiber pointer gets updated so we need a commit// to update this element.if (!updatePayload) {updatePayload = [];}} else {// For all other deleted properties we add it to the queue. We use// the whitelist in the commit phase instead.// 注意这里,加入 updatePayload 的方式是 一次加入 key, value 这2个(updatePayload = updatePayload || []).push(propKey, null);}}// 这是第二次大循环, nextProps 就是新的propsfor (propKey in nextProps) {// 处理 新旧 propsconst nextProp = nextProps[propKey];const lastProp = lastProps != null ? lastProps[propKey] : undefined;// 新props没有这个key(这个key在原型链上,不在自己),或 两个 prop 相同,或两个prop 都为 nullif (!nextProps.hasOwnProperty(propKey) ||nextProp === lastProp ||(nextProp == null && lastProp == null)) {// 符合上述条件跳过continue;}// 对于 style 类型的 props 的处理, 判断每个 style 的key是否有变化// 下面会有两个循环来处理if (propKey === STYLE) {if (__DEV__) {if (nextProp) {// Freeze the next style object so that we can assume it won't be// mutated. We have already warned for this in the past.Object.freeze(nextProp);}}if (lastProp) {// Unset styles on `lastProp` but not on `nextProp`.for (styleName in lastProp) {if (lastProp.hasOwnProperty(styleName) &&(!nextProp || !nextProp.hasOwnProperty(styleName))) {if (!styleUpdates) {styleUpdates = {};}styleUpdates[styleName] = '';}}// Update styles that changed since `lastProp`.for (styleName in nextProp) {if (nextProp.hasOwnProperty(styleName) &&lastProp[styleName] !== nextProp[styleName]) {if (!styleUpdates) {styleUpdates = {};}styleUpdates[styleName] = nextProp[styleName];}}} else {// Relies on `updateStylesByID` not mutating `styleUpdates`.if (!styleUpdates) {if (!updatePayload) {updatePayload = [];}updatePayload.push(propKey, styleUpdates);}styleUpdates = nextProp;}} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {const nextHtml = nextProp ? nextProp[HTML] : undefined;const lastHtml = lastProp ? lastProp[HTML] : undefined;if (nextHtml != null) {// 两个html不相等则加入if (lastHtml !== nextHtml) {(updatePayload = updatePayload || []).push(propKey, '' + nextHtml);}} else {// TODO: It might be too late to clear this if we have children// inserted already.}} else if (propKey === CHILDREN) {// 对于 children 的处理if (lastProp !== nextProp &&(typeof nextProp === 'string' || typeof nextProp === 'number')) {// 不同则加入(updatePayload = updatePayload || []).push(propKey, '' + nextProp);}} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||propKey === SUPPRESS_HYDRATION_WARNING) {// Noop} else if (registrationNameModules.hasOwnProperty(propKey)) {// 这里是事件绑定相关的处理if (nextProp != null) {// We eagerly listen to this even though we haven't committed yet.if (__DEV__ && typeof nextProp !== 'function') {warnForInvalidEventListener(propKey, nextProp);}ensureListeningTo(rootContainerElement, propKey);}if (!updatePayload && lastProp !== nextProp) {// This is a special case. If any listener updates we need to ensure// that the "current" props pointer gets updated so we need a commit// to update this element.updatePayload = [];}} else {// For any other property we always add it to the queue and then we// filter it out using the whitelist during the commit.// 上面都没找到,这个属性是新增属性,直接加入(updatePayload = updatePayload || []).push(propKey, nextProp);}}// 最终处理加入 styleUpdatesif (styleUpdates) {(updatePayload = updatePayload || []).push(STYLE, styleUpdates);}// 最终返回return updatePayload;
      }
      
    • diffProperties 里的 updatePayload 一开始是一个空的数组,并且最终被return
    • 对于 completeWork 来说,拿到的 updatePayload,就是 diffPropertiesprepareUpdate 返回过来的内容
    • 接下去,会有一个判断 if (updatePayload) {} 也就是说空数组也是符合这个判断条件的, 也会执行 markUpdate
    • 上述标记之后,在后续的 commit 的时候进行对应的操作
  • 以上是 updateHostComponent 的过程
    • 具体细节,参考代码里标注的中文文档和源码
    • vdom其实就是这些东西,通过props来进行 attributes 的判断和处理变化的过程
    • 主要是 整个 diffProperties 的处理

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

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

相关文章

Python基础之文件操作(I/O)

和其他编程语言一样&#xff0c;Python 也具有操作文件&#xff08;I/O&#xff09;的能力&#xff0c;比如打开文件、读取和追加数据、插入和删除数据、关闭文件、删除文件等。合理应用python提供的文件操作基本函数&#xff0c;可大大提高自动化实现的效率与框架代码的稳定性…

C++ | 六、栈 Stack、队列 Queue

栈的基础知识 栈&#xff08;stack&#xff09;是一种数据结构&#xff0c;在C中属于STL&#xff08;标准库&#xff09;特点&#xff1a;先进后出 栈的使用&#xff1a; 一、引入头文件<stack>二、创建栈变量&#xff08;类似容器、集合的创建方式&#xff09;&#xf…

C++实现函数重载的原理

一、函数重载的概念 C中允许存在同名函数&#xff0c;但要求函数参数的类型、个数不同&#xff0c;这些同名函数就称为函数的重载。 void func(int a, int b) {cout << "func(int a, int b)" << endl; }void func(double a, double b) {cout << …

【Linux】Linux编译器-gcc/g++使用

1. 背景知识 预处理&#xff08;进行宏替换) 编译&#xff08;生成汇编) 汇编&#xff08;生成机器可识别代码&#xff09; 连接&#xff08;生成可执行文件或库文件) 2. gcc如何完成 格式 gcc [选项] 要编译的文件 [选项] [目标文件] 预处理(进行宏替换) 预处理功能主要包括…

【Linux】-对于信号章节补充的知识点,以及多线程知识的汇总

&#x1f496;作者&#xff1a;小树苗渴望变成参天大树&#x1f388; &#x1f389;作者宣言&#xff1a;认真写好每一篇博客&#x1f4a4; &#x1f38a;作者gitee:gitee✨ &#x1f49e;作者专栏&#xff1a;C语言,数据结构初阶,Linux,C 动态规划算法&#x1f384; 如 果 你 …

【shell-09】 shell控制台颜色输出

echo -e echo -e 一个重要的小例子和换行符控制字符一样&#xff0c;终端颜色也有自己的十进制控制符颜色的写法颜色参考图表 echo -e 一个重要的小例子 echo -e 的意思&#xff1a;如果字符串中出现某些特定的字符组合&#xff08;转义字符&#xff09;&#xff0c;echo会将这…

大模型学习与实践笔记(十二)

使用RAG方式&#xff0c;构建opencv专业资料构建专业知识库&#xff0c;并搭建专业问答助手&#xff0c;并将模型部署到openxlab 平台 代码仓库&#xff1a;https://github.com/AllYoung/LLM4opencv 1&#xff1a;创建代码仓库 在 GitHub 中创建存放应用代码的仓库&#xff…

DAY08_SpringBoot—整合Mybatis-Plus

目录 1 MybatisPlus1.1 MP介绍1.2 MP的特点1.3 MybatisPlus入门案例1.3.1 导入jar包1.3.2 编辑POJO对象1.3.3 编辑Mapper接口1.3.4 编译YML配置文件1.3.5 编辑测试案例 1.4 MP核心原理1.4.1 需求1.4.2 原理说明1.4.3 对象转化Sql原理 1.5 MP常规操作1.5.1 添加日志打印1.5.2 测…

电脑存储位置不够怎么办

电脑内存不够怎么办&#xff01;&#xff01;&#xff01; 我前段时间经常因为电脑D盘内存不够而苦恼&#xff08;毕竟电脑内存就那么丁点&#xff0c;C盘作为系统盘不能随便下东西的情况下&#xff0c;就只能选择其他盘进 方法一&#xff1a;检查电脑硬盘的分区情况&#xf…

全国大学生智能汽车竞赛—解决Ubuntu 18.04.6 无法连接网络的问题

1.1 用到的命令 lshw &#xff08;1&#xff09;功能描述: lshw是一个提取机器硬件配置详细信息的工具&#xff0c;并且能将结果输出成HTML、json、XML等格式。 &#xff08;2&#xff09;输出形式&#xff1a; -class 仅显示一类硬件信息&#xff0c;可以使用lshw -short或ls…

网络:PPP协议

1. HDLC协议 高级链路控制协议 2. PPP协议 点对点协议&#xff0c;是point-to-point的简称。和以太网协议一样&#xff0c;PPP是数据链路层协议&#xff0c;定义了帧格式&#xff0c;称为PPP帧。 3. PPP协议与以太网协议的区别 以太网协议工作在以太网接口和以太网链路上。 以…

如何通过系统命令排查账号安全?

如何通过系统命令排查账号安全 query user 查看当前登录账号 logoff id 注销用户id net user 查看用户 net user username 查看用户登录情况 lusrmgr.msc 查看隐藏账号 winR打开regedit注册表 找到计算机\HEKY_LOCAL_MACHINE\SAM\SAM\右键给与用户读写权限 刷新打开 HKEY…

ps去除图片上的文字

1. 打开ps, 打开文件 2. 选择套索工具 3. 使用套索工具将需要去除的文字框选 4. 然后鼠标右击&#xff0c;选择内容识别填充 5. 应用确定后, 此时文字就去掉了

【Java】一文读懂逃逸分析

逃逸分析 逃逸分析&#xff08;Escape Analysis&#xff09;是一种编译器优化技术&#xff0c;它分析程序中的对象分配&#xff0c;以确定对象的作用域和生命周期。具体来说&#xff0c;逃逸分析要确定一个对象是否会逃逸出它被创建的方法或者作用域&#xff0c;换句话说&…

保姆级CISP报考攻略,让你不再迷茫

信息安全领域越来越火&#xff0c;想要在这个行业闯出一片天&#xff1f;CISP认证就是你的“敲门砖”&#xff01;想知道如何顺利考取这个超牛的证书吗&#xff1f;下面就带你一起探索保姆级CISP报考流程&#xff01;&#x1f389; &#x1f393;报考条件&#x1f393; 学历专业…

vue2中的事件修饰符

在Vue2中&#xff0c;事件修饰符是一种用于在DOM事件处理中进行特定操作的特殊标记。Vue2提供了一些内置的事件修饰符来简化事件处理逻辑。以下是Vue2中常用的事件修饰符&#xff1a; .prevent&#xff1a;阻止默认事件&#xff08;常用&#xff09;&#xff1b;.stop&#xff…

推荐在线PS修图网页版工具PHP网站源码

在线PS修图网页版工具PHP网站源码&#xff0c;PHP在线照片图片处理PS网站程序源码photoshop网页版。 有很多朋友们都是在用PS作图的&#xff0c;众所周知在使用和学习PS时是需要下载软件的&#xff0c;Photoshop软件对电脑配置也是有一定要求的&#xff0c;今天就为大家带来一…

关于C#中的Select与SelectMany方法

Select 将序列中的每个元素投影到新表单。 实例1 IEnumerable<int> squares Enumerable.Range(1, 10).Select(x > x * x);foreach (int num in squares) {Console.WriteLine(num); } /*This code produces the following output:149162536496481100 */ 实例2 str…

牛客网-----跳石头

题目描述&#xff1a; 一年一度的“跳石头”比赛又要开始了! 这项比赛将在一条笔直的河道中进行&#xff0c;河道中分布着一些巨大岩石。组委会已经选择好了两块岩石作为比赛起点和终点。在起点和终点之间&#xff0c;有N块岩石(不含起点和终点的岩石)。在比赛过程中&#xff0…

第十一章:大模型之Adaptation

参考链接&#xff1a;https://github.com/datawhalechina/so-large-lm/tree/main 1 引言 为什么需要Adaptation? 在⾃动化和⼈⼯智能的时代&#xff0c;语⾔模型已成为⼀个迅速发展的领域。从语⾔模型的训练⽅式来说&#xff0c;语⾔模型&#xff0c;例如GPT-3&#xff0c;…