React源码解读之更新的创建

news2025/7/18 8:20:24

React 的鲜活生命起源于 ReactDOM.render ,这个过程会为它的一生储备好很多必需品,我们顺着这个线索,一探婴儿般 React 应用诞生之初的悦然。

更新创建的操作我们总结为以下两种场景

  • ReactDOM.render
  • setState
  • forceUpdate

ReactDom.render

串联该内容,一图以蔽之

首先看到 react-dom/client/ReactDOM 中对于 ReactDOM 的定义,其中包含我们熟知的方法、不稳定方法以及即将废弃方法。

const ReactDOM: Object = {
  createPortal,

  // Legacy
  findDOMNode,
  hydrate,
  render,
  unstable_renderSubtreeIntoContainer,
  unmountComponentAtNode,

  // Temporary alias since we already shipped React 16 RC with it.
  // TODO: remove in React 17.
  unstable_createPortal(...args) {
    // ...
    return createPortal(...args);
  },

  unstable_batchedUpdates: batchedUpdates,

  flushSync: flushSync,

  __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
    // ...
  },
};

此处方法均来自 ./ReactDOMLegacyrender 方法定义很简单,正如我们常使用的那样,第一个参数是组件,第二个参数为组件所要挂载的DOM节点,第三个参数为回调函数。

export function render(
  element: React$Element<any>,
  container: DOMContainer,
  callback: ?Function,
) {
  // ...
  return legacyRenderSubtreeIntoContainer(
    null,
    element,
    container,
    false,
    callback,
  );
}

function legacyRenderSubtreeIntoContainer(
  parentComponent: ?React$Component<any, any>,
  children: ReactNodeList,
  container: DOMContainer,
  forceHydrate: boolean,
  callback: ?Function,
) {

  // TODO: Without `any` type, Flow says "Property cannot be accessed on any
  // member of intersection type." Whyyyyyy.
  let root: RootType = (container._reactRootContainer: any);
  let fiberRoot;
  if (!root) {
    // Initial mount
    root = container._reactRootContainer = legacyCreateRootFromDOMContainer(
      container,
      forceHydrate,
    );
    fiberRoot = root._internalRoot;
    if (typeof callback === 'function') {
      const originalCallback = callback;
      callback = function() {
        const instance = getPublicRootInstance(fiberRoot);
        originalCallback.call(instance);
      };
    }
    // 初次渲染,不会将更新标记为batched.
    unbatchedUpdates(() => {
      updateContainer(children, fiberRoot, parentComponent, callback);
    });
  } else {
    fiberRoot = root._internalRoot;
    if (typeof callback === 'function') {
      const originalCallback = callback;
      callback = function() {
        const instance = getPublicRootInstance(fiberRoot);
        originalCallback.call(instance);
      };
    }
    // Update
    updateContainer(children, fiberRoot, parentComponent, callback);
  }
  return getPublicRootInstance(fiberRoot);
}

相关参考视频讲解:进入学习

这段代码我们不难发现,调用 ReactDOM.render 时,返回的 parentComponent 是 null,并且初次渲染,不会进行批量策略的更新,而是需要尽快的完成。(batchedUpdates批量更新后续介绍)

从这部分源码我们不难看出,rendercreateProtal 的用法的联系,通过DOM容器创建Root节点的形式

function legacyCreateRootFromDOMContainer(
  container: DOMContainer,  forceHydrate: boolean,
): RootType {
  const shouldHydrate =
    forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
  // First clear any existing content.
  if (!shouldHydrate) {
    let warned = false;
    let rootSibling;
    while ((rootSibling = container.lastChild)) {
      // ...
      container.removeChild(rootSibling);
    }
  }

  return createLegacyRoot(
    container,
    shouldHydrate
      ? {
          hydrate: true,
        }
      : undefined,
  );
}

createLegacyRoot 定义于 ./ReactDOMRoot 中,指定了创建的DOM容器和一些option设置,最终会返回一个 ReactDOMBlockingRoot

export function createLegacyRoot(
  container: DOMContainer,  options?: RootOptions,
): RootType {
  return new ReactDOMBlockingRoot(container, LegacyRoot, options);
}

function ReactDOMBlockingRoot(
  container: DOMContainer,  tag: RootTag,  options: void | RootOptions,
) {
  this._internalRoot = createRootImpl(container, tag, options);
}

function createRootImpl(
  container: DOMContainer,  tag: RootTag,  options: void | RootOptions,
) {
  // Tag is either LegacyRoot or Concurrent Root
  // ...
  const root = createContainer(container, tag, hydrate, hydrationCallbacks);
  // ...
  return root;
}

关键点在于,方法最终调用了 createContainer 来创建root,而该方法中会创建我们上一节所介绍的 FiberRoot ,该对象在后续的更新调度过程中起着非常重要的作用,到更新调度内容我们详细介绍。

在这部分我们看到了两个方法,分别是:createContainer、 updateContainer,均出自 react-reconciler/inline.dom , 最终定义在 ``react-reconciler/src/ReactFiberReconciler` 。创建方法很简单,如下

export function createContainer(  containerInfo: Container,  tag: RootTag,  hydrate: boolean,  hydrationCallbacks: null | SuspenseHydrationCallbacks,): OpaqueRoot {
  return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
}

我们继续往下看,紧跟着能看到 updateContainer 方法,该方法定义了更新相关的操作,其中最重要的一个点就是 expirationTime ,直接译为中文是过期时间,我们想想,此处为何要过期时间,这个过期的含义是什么呢?这个过期时间是如何计算的呢?继续往下我们可以看到,computeExpirationForFiber 方法用于过期时间的计算,我们先将源码片段放在此处。

export function updateContainer(
  element: ReactNodeList,
  container: OpaqueRoot,
  parentComponent: ?React$Component<any, any>,
  callback: ?Function,
): ExpirationTime {
  const current = container.current;
  const currentTime = requestCurrentTimeForUpdate();
  // ...
  const suspenseConfig = requestCurrentSuspenseConfig();
  const expirationTime = computeExpirationForFiber(
    currentTime,
    current,
    suspenseConfig,
  );
  // ...

  const context = getContextForSubtree(parentComponent);
  if (container.context === null) {
    container.context = context;
  } else {
    container.pendingContext = context;
  }
  // ...

  const update = createUpdate(expirationTime, suspenseConfig);
  // Caution: React DevTools currently depends on this property
  // being called "element".  update.payload = {element};

  callback = callback === undefined ? null : callback;
  if (callback !== null) {
    warningWithoutStack(
      typeof callback === 'function',
      'render(...): Expected the last optional `callback` argument to be a ' +
        'function. Instead received: %s.',
      callback,
    );
    update.callback = callback;
  }

  enqueueUpdate(current, update);
  scheduleWork(current, expirationTime);

  return expirationTime;
}

计算完更新超时时间,而后创建更新对象 createUpdate ,进而将element绑定到update对象上,如果存在回调函数,则将回调函数也绑定到update对象上。update对象创建完成,将update添加到UpdateQueue中,关于update和UpdateQueue数据结构见上一节讲解。至此,开始任务调度。

setState 与 forceUpdate

这两个方法绑定在我们当初定义React的文件中,具体定义在 react/src/ReactBaseClasses 中,如下

Component.prototype.setState = function(partialState, callback) {
  // ...
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

这就是为何React基础上拓展React-Native能轻松自如,因为React只是做了一些规范和结构设定,具体实现是在React-Dom或React-Native中,如此达到了平台适配性。

Class组件的更新使用 this.setState ,这个api我们早已烂熟于心,对于对象组件的更新创建,定义在 react-reconciler/src/ReactFiberClassComponent.js ,classComponentUpdater对象定义了 enqueueSetStateenqueueReplaceState 以及 enqueueForceUpdate 对象方法,观察这两个方法会发现,不同在于enqueueReplaceStateenqueueForceUpdate 会在创建的update对象绑定一个tag,用于标志更新的类型是 ReplaceState 还是 ForceUpdate ,具体实现我们一起来看代码片段。

const classComponentUpdater = {
  isMounted,
  enqueueSetState(inst, payload, callback) {
    const fiber = getInstance(inst);
    const currentTime = requestCurrentTimeForUpdate();
    const suspenseConfig = requestCurrentSuspenseConfig();
    const expirationTime = computeExpirationForFiber(
      currentTime,
      fiber,
      suspenseConfig,
    );

    const update = createUpdate(expirationTime, suspenseConfig);
    update.payload = payload;
    if (callback !== undefined && callback !== null) {
      // ...
      update.callback = callback;
    }

    enqueueUpdate(fiber, update);
    scheduleWork(fiber, expirationTime);
  },
  enqueueReplaceState(inst, payload, callback) {
    const fiber = getInstance(inst);
    const currentTime = requestCurrentTimeForUpdate();
    const suspenseConfig = requestCurrentSuspenseConfig();
    const expirationTime = computeExpirationForFiber(
      currentTime,
      fiber,
      suspenseConfig,
    );

    const update = createUpdate(expirationTime, suspenseConfig);
    update.tag = ReplaceState;
    update.payload = payload;

    if (callback !== undefined && callback !== null) {
      // ...
      update.callback = callback;
    }

    enqueueUpdate(fiber, update);
    scheduleWork(fiber, expirationTime);
  },
  enqueueForceUpdate(inst, callback) {
    const fiber = getInstance(inst);
    const currentTime = requestCurrentTimeForUpdate();
    const suspenseConfig = requestCurrentSuspenseConfig();
    const expirationTime = computeExpirationForFiber(
      currentTime,
      fiber,
      suspenseConfig,
    );

    const update = createUpdate(expirationTime, suspenseConfig);
    update.tag = ForceUpdate;

    if (callback !== undefined && callback !== null) {
      // ...
      update.callback = callback;
    }

    enqueueUpdate(fiber, update);
    scheduleWork(fiber, expirationTime);
  },
};

我们也能发现,其实通过setState更新的操作实现和ReactDOM.render基本一致。

  1. 更新过期时间
  2. 创建Update对象
  3. 为update对象绑定一些属性,比如 tagcallback
  4. 创建的update对象入队 (enqueueUpdate)
  5. 进入调度过程

expirationTime的作用

expirationTime用于React在调度和渲染过程,优先级判断,针对不同的操作,有不同响应优先级,这时我们通过 currentTime: ExpirationTime 变量与预定义的优先级EXPIRATION常量计算得出expirationTime。难道currentTime如我们平时糟糕代码中的 Date.now() ?错!如此操作会产生频繁计算导致性能降低,因此我们定义currentTime的计算规则。

获取currentTime

export function requestCurrentTimeForUpdate() {
  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
    // We're inside React, so it's fine to read the actual time.
    return msToExpirationTime(now());
  }
  // We're not inside React, so we may be in the middle of a browser event.
  if (currentEventTime !== NoWork) {
    // Use the same start time for all updates until we enter React again.
    return currentEventTime;
  }
  // This is the first update since React yielded. Compute a new start time.
  currentEventTime = msToExpirationTime(now());
  return currentEventTime;
}

该方法定义了如何去获得当前时间,now 方法由 ./SchedulerWithReactIntegration 提供,对于now方法的定义似乎不太好找,我们通过断点调试 Scheduler_now ,最终能够发现时间的获取是通过 window.performance.now(), 紧接着找寻到 msToExpirationTime 定义在 ReactFiberExpirationTime.js ,定义了expirationTime相关处理逻辑。

不同的expirationTime

阅读到 react-reconciler/src/ReactFilberExpirationTime ,对于expirationTime的计算有三个不同方法,分别为:computeAsyncExpirationcomputeSuspenseExpirationcomputeInteractiveExpiration 。这三个方法均接收三个参数,第一个参数均为以上获取的 currentTime ,第二个参数为约定的超时时间,第三个参数与批量更新的粒度有关。

export const Sync = MAX_SIGNED_31_BIT_INT;
export const Batched = Sync - 1;

const UNIT_SIZE = 10;
const MAGIC_NUMBER_OFFSET = Batched - 1;

// 1 unit of expiration time represents 10ms.
export function msToExpirationTime(ms: number): ExpirationTime {
  // Always add an offset so that we don't clash with the magic number for NoWork.
  return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0);
}

export function expirationTimeToMs(expirationTime: ExpirationTime): number {
  return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
}

function ceiling(num: number, precision: number): number {
  return (((num / precision) | 0) + 1) * precision;
}

function computeExpirationBucket(
  currentTime,  expirationInMs,  bucketSizeMs,
): ExpirationTime {
  return (
    MAGIC_NUMBER_OFFSET -
    ceiling(
      MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE,
      bucketSizeMs / UNIT_SIZE,
    )
  );
}

// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
// the names to reflect.
export const LOW_PRIORITY_EXPIRATION = 5000;
export const LOW_PRIORITY_BATCH_SIZE = 250;

export function computeAsyncExpiration(
  currentTime: ExpirationTime,
): ExpirationTime {
  return computeExpirationBucket(
    currentTime,
    LOW_PRIORITY_EXPIRATION,
    LOW_PRIORITY_BATCH_SIZE,
  );
}

export function computeSuspenseExpiration(
  currentTime: ExpirationTime,  timeoutMs: number,
): ExpirationTime {
  // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
  return computeExpirationBucket(
    currentTime,
    timeoutMs,
    LOW_PRIORITY_BATCH_SIZE,
  );
}

export const HIGH_PRIORITY_EXPIRATION = __DEV__ ? 500 : 150;
export const HIGH_PRIORITY_BATCH_SIZE = 100;

export function computeInteractiveExpiration(currentTime: ExpirationTime) {
  return computeExpirationBucket(
    currentTime,
    HIGH_PRIORITY_EXPIRATION,
    HIGH_PRIORITY_BATCH_SIZE,
  );
}

重点在于 ceil 方法的定义,方法传递两个参数,需要求值的number和期望精度precision,不妨随意带入两个值观察该函数的作用,number = 100,precision = 10,那么函数返回值为 (((100 / 10) | 0) + 1) * 10,我们保持precision值不变,更改number会发现,当我们的值在100-110之间时,该函数返回的值相同。哦!此时恍然大悟,原来这个方法就是保证在同一个bucket中的更新获取到相同的过期时间 expirationTime ,就能够实现在较短时间间隔内的更新创建能够__合并处理__。

关于超时时间的处理是很复杂的,除了我们看到的 expirationTime ,还有 childExpirationTimeroot.firstPendingTimeroot.lastExpiredTimeroot.firstSuspendedTimeroot.lastSuspendedTime ,root下的相关属性标记了其下子节点fiber的expirationTime的次序,构成处理优先级的次序,childExpirationTime 则是在遍历子树时,更新其 childExpirationTime 值为子节点 expirationTime

以上是React创建更新的核心流程,任务调度我们下一章节再见。

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

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

相关文章

k8s-dynamic-pvc

安装 storage class: external-storage/nfs-client/deploy at master kubernetes-retired/external-storage GitHub 下载文件并安装: class.yaml deployment.yaml rbac.yaml 其中修改: 安装 测试: [rootmaster test-dir]# cat nginx-1.yaml apiVersion: v1 kind: Pers…

【Pytorch with fastai】第 4 章 :底层训练数字分类器

&#x1f50e;大家好&#xff0c;我是Sonhhxg_柒&#xff0c;希望你看完之后&#xff0c;能对你有所帮助&#xff0c;不足请指正&#xff01;共同学习交流&#x1f50e; &#x1f4dd;个人主页&#xff0d;Sonhhxg_柒的博客_CSDN博客 &#x1f4c3; &#x1f381;欢迎各位→点赞…

一切为了喵喵 | 攻防世界 x Nepnep x CATCTF邀你一战!

各位极客请注意❗ 各位极客请注意❗❗ 为了坚决捍卫每只小猫咪吃饱饭的权利 为了彻底贯彻“可爱就是王道”的正义 攻防世界 x Nepnep x CATCTF 邀你一战&#xff01; 此战若成&#xff0c;8333只流浪喵星人将能饱餐一顿&#xff01; 没有一只修猫咪饿肚子的明天在等着我们…

【Python】初始Python

文章目录一. Python背景知识1. Python的起源2. Python的作用3. Python的优缺点4. Python的前景二. 搭建Python环境1. 安装Python2. 安装 PyCharm一. Python背景知识 1. Python的起源 Python祖师爷吉多 范罗苏姆&#xff08;Guido van Rossum&#xff09;是一个荷兰程序员&am…

简易的Python小游戏,上班可玩一天,零基础小白可练手

文章目录 一、第一次写Python小游戏二、对小游戏进行改进 1.对玩家进行提示2.提供多次机会给玩家3.每次答案应该是随机的 三、总结 一、第一次写Python小游戏 刚开始学习Python这门计算机语言&#xff0c;所以在网上找了一个非常简易的小游戏来进行模仿编写&#xff0c;目的…

【数据挖掘】聚类分析

聚类分析 Cluster Analysis 肝到爆炸呜呜呜 一、什么是聚类分析 关键词 1️⃣ 簇 Cluster&#xff1a;数据对象的集合&#xff0c;相同簇中的数据彼此相似&#xff0c;不同簇中的数据彼此相异。 2️⃣ 聚类分析 Cluster analysis&#xff1a;根据数据特征找到数据中的相似性…

Servlet | HttpServlet源码分析、web站点的欢迎页面

目录 一&#xff1a;HttpServlet源码分析 二&#xff1a;web站点的欢迎页面 一&#xff1a;HttpServlet源码分析 1、HttpServlet类是专门为HTTP协议准备的&#xff0c;比GenericServlet更加适合HTTP协议下的开发 HttpServlet在哪个包下&#xff1f; jakarta.servlet.http.Ht…

vue - - - - vite创建vue3项目(不使用TS)

vite创建vue3项目 vite官方文档 1. 使用指令创建项目 > npm create vite your-project-name > or > yarn create vite your-project-name此处演示使用npm&#xff0c;执行该指令时&#xff0c;遇到下述7.1所示报错。 Need to install the following packages(需…

asp.net+sqlserver婚纱影楼摄影管理系统C#

目录 1绪论 5 1.1 选题背景目的和意义 5 1.2研究现状 5 1.3 课题理由 5 2系统需求分析 7 2.1可行性分析 7 2.1.1 技术可行性 7 2.1.2 经济可行性 7 2.2.3 操作可行性 8 2.2系统架构 8 2.3 业务流程分析 9 3系统总体设计 10 3.1 系统物理环…

JavaSE——异常

目录 一、基本概念 1.1 什么是异常&#xff1f; 1.2 java提供的异常处理机制有什么作用&#xff1f; 1.3 java语言中异常以什么形式存在&#xff1f; 例1&#xff1a; 二、异常处理机制 2.1 所有Exception的直接子类都叫做编译时异常 2.2 所有的RuntimeException及子类都属于…

Spring面试

1. IOC &#xff08;1&#xff09;如何实现一个IOC容器 &#xff08;2&#xff09;IOC理解 &#xff08;3&#xff09;BeanFactory BeanFactory 是 Spring 框架的基础设施&#xff0c;面向 Spring 本身&#xff1b;ApplicationContext 面向使用 Spring 框架的开发者&#xff…

Zookeeper和Eureka的区别

Zookeeper&#xff1a; CP设计(强⼀致性)&#xff0c;⽬标是⼀个分布式的协调系统&#xff0c;⽤于进⾏资源的统⼀管理。当节点crash后&#xff0c;需要进⾏leader的选举&#xff0c;在这个期间内&#xff0c;zk服务是不可⽤的。 eureka&#xff1a; AP设计&#xff08;高可用&…

动态规划--(不同的子序列,编辑距离,两个字符串的删除)

代码随想录day56 动态规划模块 不同的子序列,编辑距离&#xff0c;两个字符串的删除 文章目录1.leetcode 115. 不同的子序列1.1思路及详细步骤1.2 代码示例2.leetcode 583. 两个字符串的删除操作2.1思路及详细步骤2.2 代码示例3.leetcode 72. 编辑距离3.1思路及详细步骤3.2 代码…

绝对最直白的MySQL MVCC机制总结,免费拿走

&#x1f341; 作者&#xff1a;知识浅谈&#xff0c;CSDN签约讲师&#xff0c;后端领域优质创作者&#xff0c;阿里云社区技术博主&#xff0c;热爱分享创作 &#x1f492; 公众号&#xff1a;知识浅谈 &#x1f4cc; 擅长领域&#xff1a;全栈工程师、爬虫、ACM算法 绝对最直…

项目实战 - tpshop商城项目环境搭建

一、环境部署准备 1、软件工具准备 1.1、Vmware虚拟机 1. 在本机上安装好Vmware虚拟机 2. 在虚拟机上安装并运行Linux系统 3. 注意: 实际工具中使用云服务器 1.2、远程连接工具 1. 在本机上安装好远程连接工具 (xshell / putty / FinalShell&#xff08;推荐&#xff09;) …

三种常见的特征选择方法

特征选择 特征选择是特征工程里的一个重要问题&#xff0c;其目标是寻找最优特征子集。特征选择能剔除不相关(irrelevant)或冗余(redundant )的特征&#xff0c;从而达到减少特征个数&#xff0c;提高模型精确度&#xff0c;减少运行时间的目的。并且常能听到“数据和特征决定…

k8s master 实现高可用

Kubernetes高可用master架构 k8s的高可用&#xff0c;主要是实现Master节点的高可用。那么我们看看各个组件是如何解决高可用的。 Kubelet、Kube-proxy&#xff1a;只工作在当前Node节点上&#xff0c;无需高可用。 etcd&#xff1a;etcd如果是放在集群内部的&#xff0c;在…

长文讲解Linux内核性能优化的思路和步骤

一.性能调优简介 1.为什么要进行性能调优&#xff1f; 1&#xff09; 编写的新应用上线前在性能上无法满足需求&#xff0c;这个时候需要对系统进行性能调优 2&#xff09; 应用系统在线上运行后随着系统数据量的不断增长、访问量的不断上升&#xff0c;系统的响应速度通常越…

js-学习链表

链表基础概念 链表和数组一样&#xff0c;可以用于存储一系列连续的元素。链表中的元素在内存中不必是连续的空间。链表的每一个元素有一个由一个存储元素本身的节点和一个指向下一个元素的引用组成(指针和连接)。 链表构成 数据指针 链表优点 1.内存空间不是必须连续的&a…

实践分享:30分钟在电脑端运行小程序

预计实现效果&#xff1a;在电脑桌面端实现小程序运行 技术实现&#xff1a;小程序容器技术实现&#xff08;案例使用FinClip SDK) 技术的原理&#xff1a; 该 SDK 主要包括应用交互层、安全防护、网络通信控制和安全运行容器四个组件。 应用交互层&#xff1a;应用交互层是…