源码分析之React中的组件缓存React.memo

概述

React.memo用于缓存组件,可以避免组件不必要的更新。React.memo可以缓存函数组件和class类组件。

源码分析

React.forwardRef类似,React.memo本质上也是包装下组件,打上$$typeof标记,返回一个对象。

js 复制代码
function memo(type,compare){
    return {
        $$typeof:Symbol.for('react.memo')
        type,
        compare:compare === undefined ? null : compare
    }
}

在生成fiber时,被React.memo包装的组件对应生成的fiber.tagMemoComponent(14)

updateMemoComponent

beginWork 阶段,React.memo会调用updateMemoComponent来处理子节点fiber

js 复制代码
function updateMemoComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes,
) {
  // 首次渲染,挂载时
  if (current === null) {
    // 获取memo包裹的组件
    const type = Component.type;
    // 若包裹的组件是一个函数组件并且没有传递比较函数compare
    if (isSimpleFunctionComponent(type) && Component.compare === null) {
      let resolvedType = type;
      // 修改fiber的tag和type
      workInProgress.tag = SimpleMemoComponent;
      workInProgress.type = resolvedType;
      // 调用updateSimpleMemoComponent方法,并返回
      return updateSimpleMemoComponent(
        current,
        workInProgress,
        resolvedType,
        nextProps,
        renderLanes,
      );
    }
    // 若包裹的组件不是一个函数组件或者compare不为null,则调用createFiberFromTypeAndProps重新生成一个fiber作为子节点
    const child = createFiberFromTypeAndProps(
      Component.type,
      null,
      nextProps,
      workInProgress,
      workInProgress.mode,
      renderLanes,
    );
    // 将当前fiber的ref赋值给子节点
    child.ref = workInProgress.ref;
    // 维护父子fiber指向
    child.return = workInProgress;
    workInProgress.child = child;
    // 返回子fiber
    return child;
  }
  
  // 若是更新阶段
  
  // 取旧fiber上的子节点
  const currentChild = current.child; 
  
  // 判断是否需要安排更新:调用checkScheduledUpdateOrcontext检测
  const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(
    current,
    renderLanes,
  );
  // 若不需要更新,
  if (!hasScheduledUpdateOrContext) {
    // 从旧fiber上取出旧属性
    const prevProps = currentChild.memoizedProps;
    
    // 判断是否传了检测函数,若没传,则采用shallowEqual进行浅比较
    let compare = Component.compare;
    compare = compare !== null ? compare : shallowEqual;
    // 比较新旧属性是否发生改变以及新旧fiber的ref是否发生了改变
    if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
      // 若满足条件,则调用bailoutOnAlreadyFinishedWork进入bailout优化机制
      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
    }
  }
  
  // 若需要更新,则调用createWorkInProgress创建子fiber
  const newChild = createWorkInProgress(currentChild, nextProps);
  // 传递ref
  newChild.ref = workInProgress.ref;
  // 保证指向
  newChild.return = workInProgress;
  workInProgress.child = newChild;
  // 最后返回子fiber
  return newChild;
}

updateSimpleMemoComponent

React.memo包装的是一个函数组件,且没有自定义compare方法,则React会将当做一个SimpleMemoComponent类型的fiber来处理,调用updateSimpleMemoComponent方法处理子节点,即包裹的函数组件。

js 复制代码
function updateSimpleMemoComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes,
) {
  // 判断旧fiber是否存在,
  if (current !== null) {
  // 若存在,则说明是更新操作
    // 获取旧fiber上的旧属性
    const prevProps = current.memoizedProps;
    // 调用shallowEqual方法判断属性是否发生变化,若未变化,且ref没变
    if (
      shallowEqual(prevProps, nextProps) &&
      current.ref === workInProgress.ref
    ) {
      // 则将didReceiveUpdate置为false,表示要短路更新
      didReceiveUpdate = false;
      // 将旧属性赋值给新属性以及fiber上的属性
      workInProgress.pendingProps = nextProps = prevProps;
      // 调用checkScheduledUpdateOrContext检测子组件是否有更新以及context是否有变化,若未变化,则进入bailout优化
      if (!checkScheduledUpdateOrContext(current, renderLanes)) {
        workInProgress.lanes = current.lanes;
        return bailoutOnAlreadyFinishedWork(
          current,
          workInProgress,
          renderLanes,
        );
      } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
      // 若上述条件不满足,且flags上有强制更新,则将didReceiveUpdate置为true
        didReceiveUpdate = true;
      }
    }
  }

  // 旧Fiber不存在,说明是挂载操作,首次渲染直接调用updateFunctionComponent方法,并返回其结果 
  return updateFunctionComponent(
    current,
    workInProgress,
    Component,
    nextProps,
    renderLanes,
  );
}

辅助方法

shallowEqual

shallowEqual方法用于浅比较两个对象是否相等。isObject.is,是 JavaScript 中用于判断两个值是否严格相等的方法。

js 复制代码
function shallowEqual(objA, objB) {
  // 首先判断objA与objB是否严格相等,
  if (is(objA, objB)) {
    return true;
  }
  
  // 检测objA,objB的类型
  if (
    typeof objA !== 'object' ||
    objA === null ||
    typeof objB !== 'object' ||
    objB === null
  ) {
    return false;
  }
  
  // 获取objA,objB的key值数组
  const keysA = Object.keys(objA);
  const keysB = Object.keys(objB);
  
  // 若key的长度不相等,则返回false
  if (keysA.length !== keysB.length) {
    return false;
  }
  
  // 比较objA和objB的属性值是否相等
  for (let i = 0; i < keysA.length; i++) {
    const currentKey = keysA[i];
    if (
      !hasOwnProperty.call(objB, currentKey) ||
      !is(objA[currentKey], objB[currentKey])
    ) {
      return false;
    }
  }

  return true;
}
相关推荐
zhifou1234567 小时前
Vue基础(二)
前端·javascript·vue.js
两只羊ovo7 小时前
手写一个最小版 Claude Code:从任务拆解到 Agent Loop 转起来
前端
给个offer养家糊口7 小时前
抽离 elpis npm 包
前端
默_笙7 小时前
🙃 我让爬虫终于看到了我的网站,后端同事说"这也行?"(下):App Router 全栈实战
前端·javascript
葡萄城技术团队8 小时前
一个单元格放置两个日期选择器:用 SpreadJS CellButtons 录入日期范围
前端
马可家的菠萝9 小时前
自动保存已经有了,为什么笔记软件还需要“历史版本”?
前端·后端·架构
半个落月9 小时前
从 "use client" 到 Route Handler:用 Todos 理解 Next.js 水合与全栈请求
前端·react.js·next.js
qq_452396239 小时前
第七篇:《大型前端项目的模块化与目录结构设计》
前端
你脑门上的脚印9 小时前
Vue 项目从零实现语音转文字、文字转语音功能(完整可用 + 踩坑指南)
前端·vue.js
paopaokaka_luck10 小时前
基于springboot3+vue3的车间生产管理系统(Echarts图形化分析、BI报表)
java·前端·spring boot·学习·echarts