React16源码: React中commit阶段的commitBeforeMutationLifecycles的源码实现

news/2024/7/15 17:23:24 标签: react.js, 前端, 前端框架

commitBeforeMutationLifecycles


1 )概述

  • 在 react commit阶段的 commitRoot 第一个while循环中
  • 调用了 commitBeforeMutationLifeCycles
  • 现在来看下,里面发生了什么

2 )源码

回到 commit 阶段的第一个循环中,在 commitRoot 函数里
定位到 packages/react-reconciler/src/ReactFiberScheduler.js#L647

看这里

// Invoke instances of getSnapshotBeforeUpdate before mutation.
nextEffect = firstEffect;
startCommitSnapshotEffectsTimer();

// 接下去就进入了三个循环:
// 第一个循环主要是 commitBeforeMutationLifecycles,这个方法它其实很简单,它是这三个循环当中最简单的一个方法
// 它唯一的作用就是调用 ClassComponent 上面可能会存在的 getSnapshotBeforeUpdate 这么一个生命周期方法
while (nextEffect !== null) {
  let didError = false;
  let error;
  if (__DEV__) {
    invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
    if (hasCaughtError()) {
      didError = true;
      error = clearCaughtError();
    }
  } else {
    try {
      commitBeforeMutationLifecycles();
    } catch (e) {
      didError = true;
      error = e;
    }
  }
  if (didError) {
    invariant(
      nextEffect !== null,
      'Should have next effect. This error is likely caused by a bug ' +
        'in React. Please file an issue.',
    );
    captureCommitPhaseError(nextEffect, error);
    // Clean-up
    if (nextEffect !== null) {
      nextEffect = nextEffect.nextEffect;
    }
  }
}
  • 在开始循环之前都会用到一个全局变量叫做 nextEffect,当然它一开始是 firstEffect
    • 是在 RootFiber 上面,它的 firstEffect 到 lastEffect 这个链表上面的第一个effect
    • 也就是第一个需要我们commit的fiber对象
  • 需要注意一点,这边有一个很奇怪的代码,就是我们这个 commitBeforeMutationLifecycles 方法
    • 可以看到 import { commitBeforeMutationLifeCycles } from './ReactFiberCommitWork'
    • 但是又在本文件中,定义了一个同名的方法
      // 这个是核心
      function commitBeforeMutationLifecycles() {
        while (nextEffect !== null) {
          if (__DEV__) {
            ReactCurrentFiber.setCurrentFiber(nextEffect);
          }
      
          const effectTag = nextEffect.effectTag;
          if (effectTag & Snapshot) {
            recordEffect();
            const current = nextEffect.alternate;
            commitBeforeMutationLifeCycles(current, nextEffect); // 这个函数,不是上层的自己,而是 import 进来的
          }
      
          nextEffect = nextEffect.nextEffect;
        }
      
        if (__DEV__) {
          ReactCurrentFiber.resetCurrentFiber();
        }
      }
      
  • 这个操作会有点奇怪,因为正常来讲,import 进来的内容,它是一个常量,它不应该是能够直接被修改
  • 注意,在 commitRoot 里调用的 commitBeforeMutationLifeCycles 是文件内的这个方法
  • 而文件内的这个方法,调用的 commitBeforeMutationLifeCycles 是 import 进来的
    • 它来自于 packages/react-reconciler/src/ReactFiberCommitWork.js#L215
  • 它通过一个while循环,循环的是我们的 effect链
    • 在这个循环的后面,可以看到 nextEffect = nextEffect.nextEffect;
  • 这就是说一个一个往下这么去循环,对 有 Snapshot 这个 SideEffect 的节点执行了下面的方法

再次定位到 packages/react-reconciler/src/ReactFiberCommitWork.js#L215

进入 commitBeforeMutationLifeCycles 这个就是上面定义的同名函数里面调用的方法

function commitBeforeMutationLifeCycles(
  current: Fiber | null,
  finishedWork: Fiber,
): void {
  switch (finishedWork.tag) {
    case FunctionComponent:
    case ForwardRef:
    case SimpleMemoComponent: {
      commitHookEffectList(UnmountSnapshot, NoHookEffect, finishedWork);
      return;
    }
    case ClassComponent: {
      if (finishedWork.effectTag & Snapshot) {
        if (current !== null) {
          const prevProps = current.memoizedProps;
          const prevState = current.memoizedState;
          startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
          const instance = finishedWork.stateNode;
          // We could update instance props and state here,
          // but instead we rely on them being set during last render.
          // TODO: revisit this when we implement resuming.
          if (__DEV__) {
            if (finishedWork.type === finishedWork.elementType) {
              warning(
                instance.props === finishedWork.memoizedProps,
                'Expected instance props to match memoized props before ' +
                  'getSnapshotBeforeUpdate. This is likely due to a bug in React. ' +
                  'Please file an issue.',
              );
              warning(
                instance.state === finishedWork.memoizedState,
                'Expected instance state to match memoized state before ' +
                  'getSnapshotBeforeUpdate. This is likely due to a bug in React. ' +
                  'Please file an issue.',
              );
            }
          }
          const snapshot = instance.getSnapshotBeforeUpdate(
            finishedWork.elementType === finishedWork.type
              ? prevProps
              : resolveDefaultProps(finishedWork.type, prevProps),
            prevState,
          );
          if (__DEV__) {
            const didWarnSet = ((didWarnAboutUndefinedSnapshotBeforeUpdate: any): Set<
              mixed,
            >);
            if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
              didWarnSet.add(finishedWork.type);
              warningWithoutStack(
                false,
                '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' +
                  'must be returned. You have returned undefined.',
                getComponentName(finishedWork.type),
              );
            }
          }
          instance.__reactInternalSnapshotBeforeUpdate = snapshot;
          stopPhaseTimer();
        }
      }
      return;
    }
    case HostRoot:
    case HostComponent:
    case HostText:
    case HostPortal:
    case IncompleteClassComponent:
      // Nothing to do for these component types
      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.',
      );
    }
  }
}
  • 它传入的 current 是 workInProgress 对象,也就是fiber对象
  • 然后传入的 nextEfect 是 finishedWork 对象
  • 通过 instance.getSnapshotBeforeUpdate 传入两个 props 来获取 snapshot 快照对象
  • 之后将 snapshot 挂载到 instance.__reactInternalSnapshotBeforeUpdate
  • 对于其他类型的组件,它都没有任何的处理,只处理了 ClassComponent
  • 因为对这种情况来说,只有 ClassComponent 有这个 SideEffect
  • 并且会有 getSnapshotBeforeUpdate 这个生命周期方法的

http://www.niftyadmin.cn/n/5346894.html

相关文章

【微信小程序】图片违法违规内容鉴别(云函数)

微信小程序通过云调用校验一张图片是否含有违法违规内容。 选择图片: wx.chooseImage({count: 6,sizeType: [compressed], // 可以指定是原图还是压缩图&#xff0c;默认二者都有sourceType: [album, camera], // 可以指定来源是相册还是相机&#xff0c;默认二者都有success: …

python连接sqlserver

1、安装sqlserver 用的是sqlserver2012的版本 网上很多&#xff0c;参考下 https://blog.csdn.net/weixin_44889709/article/details/123769722 2、安装python3.7及以下环境 尝试安装python3.8的环境不能连接成功 conda create -n pytorch python3.73、安装sqlserver的pyt…

数据结构——静态链表

1.定义&#xff1a; &#xff08;1&#xff09;单链表&#xff1a;各个结点散落在内存中的各个角落&#xff0c;每个结点有指向下一个节点的指针(下一个结点在内存 中的地址); &#xff08;2&#xff09;静态链表&#xff1a;用数组的方式来描述线性表的链式存储结构: 分配一…

nginx安装ssl模块http_ssl_module

查看nginx安装的模块 /usr/local/nginx/sbin/nginx -V若出现“–with-http_ssl_module”说明已经安装过&#xff0c;否则继续执行下列步骤 进入nginx源文件目录 cd /usr/local/nginx/nginx-1.20.2重新编译nginx ./configure --with-http_ssl_module如果组件linux缺少&…

计算机网络 第6章(应用层)

系列文章目录 计算机网络 第1章&#xff08;概述&#xff09; 计算机网络 第2章&#xff08;物理层&#xff09; 计算机网络 第3章&#xff08;数据链路层&#xff09; 计算机网络 第4章&#xff08;网络层&#xff09; 计算机网络 第5章&#xff08;运输层&#xff09; 计算机…

CSS 实现 flex布局最后一行左对齐的方案「多场景、多方案」

目录 前言解决方案场景一、子项宽度固定&#xff0c;每一行列数固定方法一&#xff1a;模拟两端对齐方法二&#xff1a;根据元素个数最后一个元素动态margin 场景二、子项的宽度不确定方法一&#xff1a;直接设置最后一项 margin-right:auto方法二&#xff1a;使用:after(伪元素…

使用阿里云的oss对象存储服务实现图片上传(前端vue后端java详解)

一&#xff1a;前期准备&#xff1a; 1.1&#xff1a;注册阿里云账号&#xff0c;开启对象存储oss功能&#xff0c;创建一个bucket&#xff08;百度教程多的是&#xff0c;跟着创建一个就行&#xff0c;创建时注意存储类型是标准存储&#xff0c;读写权限是公共读&#xff09;…

Leetcode:二分搜索树层次遍历

题目&#xff1a; 给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。 示例&#xff1a; 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;[[3],[9,…