React16源码: React中commitAllHostEffects内部的commitWork的源码实现

commitWork


1 )概述

  • 在 react commit 阶段的 commitRoot 第二个while循环中
  • 调用了 commitAllHostEffects,这个函数不仅仅处理了新增节点,
  • 若一个节点已经存在,当它有新的内容要更新或者是它的attributes要更新
  • 这个时候,就需要调用 commitWork

2 )源码

定位到 packages/react-reconciler/src/ReactFiberCommitWork.js#L1033

function commitWork(current: Fiber | null, finishedWork: Fiber): void {if (!supportsMutation) {switch (finishedWork.tag) {case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent: {commitHookEffectList(UnmountMutation, MountMutation, finishedWork);return;}}commitContainer(finishedWork);return;}// 首先,根据不同的tag类型来执行不同的操作switch (finishedWork.tag) {case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent: {commitHookEffectList(UnmountMutation, MountMutation, finishedWork);return;}// ClassComponent 不在这里的执行范围内,所以它就return了case ClassComponent: {return;}case HostComponent: {const instance: Instance = finishedWork.stateNode;// // 如果instance不等于null,就代表 instance 对应的节点已经创建了if (instance != null) {// Commit the work prepared earlier.const newProps = finishedWork.memoizedProps;// For hydration we reuse the update path but we treat the oldProps// as the newProps. The updatePayload will contain the real change in// this case.const oldProps = current !== null ? current.memoizedProps : newProps;const type = finishedWork.type;// TODO: Type the updateQueue to be specific to host components.// 获取了一个 updatePayload 等于 finishedWork.updateQueue// 在 completeWork 的时候,对于 HostComponent 进行了新老 props 的一个对比// 这个对比的结果就是返回一个叫做 updatePayload 这么一个数组// 这个数组是以2为单位,就是说一个key一个value, 它的第一位是key,第二位是value,然后这样的形式一个一个往后面堆叠// 拿到这么一个 updatePayload 之后,我们就知道在commit阶段要去执行怎么样的一个更新操作const updatePayload: null | UpdatePayload = (finishedWork.updateQueue: any);finishedWork.updateQueue = null;// 存在 updatePayload 则执行 commitUpdateif (updatePayload !== null) {commitUpdate(instance,updatePayload,type,oldProps,newProps,finishedWork,);}}return;}case HostText: {invariant(finishedWork.stateNode !== null,'This should have a text node initialized. This error is likely ' +'caused by a bug in React. Please file an issue.',);const textInstance: TextInstance = finishedWork.stateNode;const newText: string = finishedWork.memoizedProps;// For hydration we reuse the update path but we treat the oldProps// as the newProps. The updatePayload will contain the real change in// this case.const oldText: string =current !== null ? current.memoizedProps : newText;commitTextUpdate(textInstance, oldText, newText);return;}case HostRoot: {return;}case Profiler: {return;}case SuspenseComponent: {let newState: SuspenseState | null = finishedWork.memoizedState;let newDidTimeout;let primaryChildParent = finishedWork;if (newState === null) {newDidTimeout = false;} else {newDidTimeout = true;primaryChildParent = finishedWork.child;if (newState.timedOutAt === NoWork) {// If the children had not already timed out, record the time.// This is used to compute the elapsed time during subsequent// attempts to render the children.newState.timedOutAt = requestCurrentTime();}}if (primaryChildParent !== null) {hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);}return;}case IncompleteClassComponent: {return;}default: {invariant(false,'This unit of work tag should not have side-effects. This error is ' +'likely caused by a bug in React. Please file an issue.',);}}
}
  • 进入 commitUpdate

    // packages/react-dom/src/client/ReactDOMHostConfig.js#L324
    export function commitUpdate(domElement: Instance,updatePayload: Array<mixed>,type: string,oldProps: Props,newProps: Props,internalInstanceHandle: Object,
    ): void {// Update the props handle so that we know which props are the ones with// with current event handlers.updateFiberProps(domElement, newProps); // 将新的props挂载到新的属性上// Apply the diff to the DOM node.updateProperties(domElement, updatePayload, type, oldProps, newProps);
    }// packages/react-dom/src/client/ReactDOMComponentTree.js#L85
    export function updateFiberProps(node, props) {node[internalEventHandlersKey] = props;
    }// packages/react-dom/src/client/ReactDOMComponent.js#L775
    // Apply the diff.
    export function updateProperties(domElement: Element,updatePayload: Array<any>,tag: string,lastRawProps: Object,nextRawProps: Object,
    ): void {// Update checked *before* name.// In the middle of an update, it is possible to have multiple checked.// When a checked radio tries to change name, browser makes another radio's checked false.// 像是 radio 可以设置 value 绑定来设置// 对于radio标签,设置通过 value 的绑定来进行是否选中的控制, 相当于是要把value转化成哪一个radio标签,它的checked属性是等于true的这么一种情况// 这是为什么当初在执行 diff property 的时候,判断如果这个标签是input,它的 updatePayload 直接等于了一个空数组// 也就是说,即便我们后续 updatePayload 的里面没有放任何的内容,但它返回的仍然是一个空数组,仍然要执行到我们这个 updateProperties 方法里面// 因为最终我们要去根据一些不同的情况来更新,像radio标签,checkbox 标签 的一个 checked 相关的一些状态if (tag === 'input' &&nextRawProps.type === 'radio' &&nextRawProps.name != null) {ReactDOMInput.updateChecked(domElement, nextRawProps);}const wasCustomComponentTag = isCustomComponent(tag, lastRawProps);const isCustomComponentTag = isCustomComponent(tag, nextRawProps);// Apply the diff.// 更新 dom 节点的 propertiesupdateDOMProperties(domElement,updatePayload,wasCustomComponentTag,isCustomComponentTag,);// TODO: Ensure that an update gets scheduled if any of the special props// changed.// 表单标签的处理// 其实就是把这些 input, textarea, select 标签, 特殊的一些属性,一些 attribute 给它进行一个更新的一个过程switch (tag) {case 'input':// Update the wrapper around inputs *after* updating props. This has to// happen after `updateDOMProperties`. Otherwise HTML5 input validations// raise warnings and prevent the new value from being assigned.ReactDOMInput.updateWrapper(domElement, nextRawProps);break;case 'textarea':ReactDOMTextarea.updateWrapper(domElement, nextRawProps);break;case 'select':// <select> value update needs to occur after <option> children// reconciliationReactDOMSelect.postUpdateWrapper(domElement, nextRawProps);break;}
    }// packages/react-dom/src/client/ReactDOMInput.js#L128
    export function updateChecked(element: Element, props: Object) {const node = ((element: any): InputWithWrapperState);const checked = props.checked;if (checked != null) {// dom操作DOMPropertyOperations.setValueForProperty(node, 'checked', checked, false);}
    }// packages/react-dom/src/shared/isCustomComponent.js#L10
    function isCustomComponent(tagName: string, props: Object) {// 它根据标签名字上,是否有 - 的存在, 并且 props.is 是 string 则是if (tagName.indexOf('-') === -1) {return typeof props.is === 'string';}// 有 - 的,屏蔽自有的一些,排除之后其他都算 自定义switch (tagName) {// These are reserved SVG and MathML elements.// We don't mind this whitelist too much because we expect it to never grow.// The alternative is to track the namespace in a few places which is convoluted.// https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-conceptscase 'annotation-xml':case 'color-profile':case 'font-face':case 'font-face-src':case 'font-face-uri':case 'font-face-format':case 'font-face-name':case 'missing-glyph':return false;default:return true;}
    }// packages/react-dom/src/client/ReactDOMComponent.js#L326
    function updateDOMProperties(domElement: Element,updatePayload: Array<any>,wasCustomComponentTag: boolean,isCustomComponentTag: boolean,
    ): void {// TODO: Handle wasCustomComponentTag// 遍历这个updatepaylow的这个数组,然后记住这边的下标增加是每次加2,而不是加1了for (let i = 0; i < updatePayload.length; i += 2) {// i 对应的就是 propKey, 然后i加1对应的就是 propValueconst propKey = updatePayload[i];const propValue = updatePayload[i + 1];// 如果是style,会对每一个style的属性来执行if (propKey === STYLE) {// 里面会遍历这个style对象里面的每一个style属性,然后去设置对应的值// 我们拿到一个对象,最终如何给它转换成真正的CSS属性给它设置上去的一个过程// 其中还要考虑一些属性是删除的操作CSSPropertyOperations.setValueForStyles(domElement, propValue);} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {setInnerHTML(domElement, propValue);} else if (propKey === CHILDREN) {setTextContent(domElement, propValue);} else {// 对于其他属性的处理DOMPropertyOperations.setValueForProperty(domElement,propKey,propValue,isCustomComponentTag,);}}
    }
    // packages/react-dom/src/client/ReactDOMHostConfig.js#L343
    export function commitTextUpdate(textInstance: TextInstance,oldText: string,newText: string,
    ): void {textInstance.nodeValue = newText;
    }
    
  • 对于 HostComponent 来说

    • 因为更新的过程,有一大部分是放在 completeUnitOfWork 里面去做了
    • completeWork 的时候会获得这个 updatePayload
    • 这个 payload 已经告诉我们具体要做哪些属性的操作了
    • 它里面也包含了我们有一些 attribute 要删除的情况
    • 就是说它的 value 为 null 的情况, 标示着这个属性是要被删除的
    • 所以, 那一部分工作做完了之后,到这里其实已经比较的简单了
    • 只需要根据 updatePayload 里面相关的内容进行一个整体的更新就可以了
  • 对于 HostText 它也要进行一个更新,它调用了一个 commitTextUpdate

  • 以上就是整个 commitWork 里面做的事情, 具体的细节写在代码注释里

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

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

相关文章

向量数据库知识积累

前言 前文4篇文章主要介绍了MySQL与Redis相关知识&#xff0c;可能某些同学看来略显枯燥。本文基于最近大热的aigc&#xff0c;介绍其中的核心工具&#xff0c;内部数据存储&#xff1a;向量数据库。本人在最近的项目中也是初次使用了向量数据库&#xff0c;对其中的向量处理、…

臻于至善,CodeArts Snap 二维绘图来一套不?

前言 我在体验 华为云的 CodeArts Snap 时&#xff0c;第一个例子就是绘制三角函数图像&#xff0c;功能注释写的也很简单。 业务场景中&#xff0c;有一类就是需要产出各种二维图形的&#xff0c;比如&#xff0c;折线图、散点图、柱状图等。 为了提前积累业务素材&#xf…

Docker数据卷挂载(以容器化Mysql为例)

数据卷 数据卷是一个虚拟目录&#xff0c;是容器内目录与****之间映射的桥梁 在执行docker run命令时&#xff0c;使用**-v 本地目录&#xff1a;容器目录**可以完成本地目录挂载 eg.Mysql容器的数据挂载 1.在根目录root下创建目录mysql及三个子目录&#xff1a; cd ~ pwd m…

GitBook可以搭建知识库吗?有无其他更好更方便的?

在一个现代化的企业中&#xff0c;知识是一项宝贵的资产。拥有一个完善的企业知识库&#xff0c;不仅可以加速员工的学习和成长&#xff0c;还能提高工作效率和团队协作能力。然而&#xff0c;随着企业不断发展和扩大规模&#xff0c;知识库的构建和管理变得更加复杂和耗时。 |…

mysql的联合索引利用情况

目录 查询条件对应的列值的类型与列对应的类型不一致 只有一个联合索引且包含非主键外全部列 查询条件全部为等值查询 查询条件有范围查询 有联合索引未包含全部列 在使用 mysql 进行数据存储时&#xff0c;经常用到联合索引&#xff0c;但是使用联合索引有一些注意点&…

git checkout和git switch的区别

git checkout 和 git switch 是 Git 中用于切换分支的命令&#xff0c;但它们在某些方面有一些区别。需要注意的是&#xff0c;git switch 是在 Git 2.23 版本引入的&#xff0c;它提供了一种更直观的分支切换方式。 git checkout&#xff1a; 分支切换&#xff1a; 在 Git 2.…

初学数据结构:Java对象的比较

目录 1. PriorityQueue中插入对象2. 元素的比较2.1 基本类型的比较2.2 对象比较的问题 3. 对象的比较3.1 基于Comparable接口类的比较3.2 基于比较器比较3.3 三种方式对比 4. 集合框架中PriorityQueue的比较方式5. 使用PriorityQueue创建大小堆&#xff0c;解决TOPK问题 【本节…

PyTorch 中的nn.Conv2d 类

nn.Conv2d 是 PyTorch 中的一个类&#xff0c;代表二维卷积层&#xff08;2D Convolution Layer&#xff09;。这个类广泛用于构建卷积神经网络&#xff08;CNN&#xff09;&#xff0c;特别是在处理图像数据时。 基本概念 卷积: 在神经网络的上下文中&#xff0c;卷积是一种特…

llamaindex 集成本地大模型

从​​​​​​​​​​​​​​用llamaindex 部署本地大模型 - 知乎Customizing LLMs within LlamaIndex Abstractions 目的&#xff1a;llamaindex 是一个很好的应用框架&#xff0c;基于此搭建一个RAG应用是一个不错的选择&#xff0c;但是由于llamaindex默认设置是openai的…

FlashInternImage实战:使用FlashInternImage实现图像分类任务(一)

文章目录 摘要安装包安装timm 数据增强Cutout和MixupEMA项目结构编译安装DCNv4环境安装过程配置CUDAHOME解决权限不够的问题 按装ninja编译DCNv4 计算mean和std生成数据集 摘要 https://arxiv.org/pdf/2401.06197.pdf 论文介绍了Deformable Convolution v4&#xff08;DCNv4&…

【MQ02】基础简单消息队列应用

基础简单消息队列应用 在上一课中&#xff0c;我们已经学习到了什么是消息队列&#xff0c;有哪些消息队列&#xff0c;以及我们会用到哪个消息队列。今天&#xff0c;就直接进入主题&#xff0c;学习第一种&#xff0c;最简单&#xff0c;但也是最常用&#xff0c;最好用的消息…

百度百科词条编辑规则是什么?

百度百科词条编辑规则是指在百度百科平台上编辑和创建词条时需要遵循的一系列标准和指南。百度百科作为全球最大的中文百科全书&#xff0c;旨在为用户提供准确、全面、客观的知识信息。为了确保词条内容的质量&#xff0c;百度设定了严格的编辑规则。伯乐网络传媒来给大家分享…

用navigator.sendBeacon完成网页埋点异步请求记录用户行为,当网页关闭的时候,依然后完美完成接口请求,不会因为浏览器关闭了被中断请求。

代码用例 <template><div :class"$options.name"><el-button type"primary" click"sendBeacon">navigator.sendBeacon 请求埋点接口 发送json对象数据</el-button></div> </template><script> expor…

java web 职位推荐系系统Myeclipse开发mysql数据库协同过滤算法java编程计算机网页项目

一、源码特点 java Web职位推荐系统是一套完善的java web信息管理系统 &#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0…

【小白教程】幻兽帕鲁服务器一键搭建 | 支持更新 | 自定义配置

幻兽帕鲁刚上线就百万在线人数&#xff0c;官方服务器的又经常不稳定&#xff0c;所以这里给大家带来最快捷的搭建教程&#xff0c;废话不多说直接开始。 步骤一&#xff1a;准备服务器 服务器建议 Linux 系统&#xff0c;资源占用低&#xff0c;而且一键脚本只需要一条命令&am…

安卓程序开发——搭建主页框架

一、实验目的 搭建项目框架掌握Android Activity组件使用和Intent机制&#xff0c;加强对Activity生命周期的理解&#xff0c;掌握Fragment的使用。 二、实验设备及器件 Android Studio 三、实验内容 1.创建一个Android应用&#xff0c;设置工程名MobileShop&#xff0c;包…

react的高阶函数HOC:

React 的高阶组件&#xff08;Higher-Order Component&#xff0c;HOC&#xff09;是一种用于复用组件逻辑的模式。它是一个函数&#xff0c;接收一个组件作为参数&#xff0c;并返回一个新的增强过的组件。 HOC 可以用于实现以下功能&#xff1a; 代码复用&#xff1a;通过将…

Android主流框架汇总

Android主流框架汇总 Android 百大框架 Android 常用开发框架 Android MVP 快速开发框架 Android 开源框架【集合】 AndroidFire 新闻阅读App框架 RxPermissions——Android 申请运行时权限 RxPermissions——Android 动态权限申请库 SuperTextView——绘制控件UI XPopup——An…

linux系统nginx工具接口压力测试工具和关联php页面

接口压力测试工具和nginx关联php ab接口压力测试工具工具下载与使用参数选项内容解释ab性能指标吞吐率&#xff08;Requests per second&#xff09;并发连接数&#xff08;The number of concurrent connections&#xff09;并发用户数&#xff08;Concurrency Level&#xff…

携程开源 基于真实请求与数据的流量回放测试平台、自动化接口测试平台AREX

携程开源 基于真实请求与数据的流量回放测试平台、自动化接口测试平台AREX 官网文档 基于真实请求与数据的流量回放测试平台、自动化接口测试平台AREX 这篇文章稍稍水一下&#xff0c;主要讲下部署过程里踩的坑&#xff0c;因为部署的过程主要是运维同学去处理了&#xff0c;我…