返回

React 源码解析之 FunctionComponent(下)

前端

React 源码解析之 FunctionComponent(下)

前言

在 React 源码解析之 FunctionComponent(中)中,讲到了 reconcileSingleElement()reconcileSingleTextNode()

function reconcileSingleElement(
  returnFiber,
  currentFirstChild,
  element,
  nextUnitOfWork,
) {
  const key = element.key;
  let child = currentFirstChild;
  while (child !== null) {
    if (child.key === key) {
      if (child.type === element.type) {
        // ...
      } else {
        // ...
      }
      return nextUnitOfWork;
    }
    child = child.sibling;
  }

  // ...
}

function reconcileSingleTextNode(
  returnFiber,
  currentFirstChild,
  textNode,
  nextUnitOfWork,
) {
  if (currentFirstChild !== null && currentFirstChild.nodeType === 3) {
    // ...
    return nextUnitOfWork;
  }

  // ...
}

接下来,我们讲 reconcileChildren() 函数:

function reconcileChildren(returnFiber, currentFirstChild, newChild, nextUnitOfWork) {
  // ...

  // 如果 newChild 是一个文本节点,则调用 reconcileSingleTextNode() 来处理它
  if (typeof newChild === 'string' || typeof newChild === 'number') {
    return reconcileSingleTextNode(returnFiber, currentFirstChild, newChild, nextUnitOfWork);
  }

  // 如果 newChild 是一个元素,则调用 reconcileSingleElement() 来处理它
  if (typeof newChild === 'object' && newChild !== null) {
    return reconcileSingleElement(returnFiber, currentFirstChild, newChild, nextUnitOfWork);
  }

  // ...
}

reconcileChildren() 函数首先检查 newChild 的类型,如果是文本节点,则调用 reconcileSingleTextNode() 函数来处理它,如果是元素,则调用 reconcileSingleElement() 函数来处理它。

reconcileSingleElement() 函数中,首先会遍历 currentFirstChild,检查是否存在与 newChild 具有相同 key 的子元素。如果存在,则会比较它们的类型,如果类型相同,则会更新该子元素,否则会创建一个新的子元素。如果 currentFirstChild 中没有与 newChild 具有相同 key 的子元素,则会创建一个新的子元素。

reconcileSingleTextNode() 函数中,首先会检查 currentFirstChild 是否是文本节点,如果是,则会比较它的文本内容与 newChild 的文本内容,如果相同,则会更新该文本节点,否则会创建一个新的文本节点。如果不是,则会创建一个新的文本节点。

总结

在本文中,我们解析了 React 源码中的 reconcileChildren()reconcileSingleElement()reconcileSingleTextNode() 函数,了解了 React 如何处理子元素、元素和文本节点。这些函数对于理解 React 的工作原理至关重要,希望能够帮助读者更好地掌握 React 的核心概念。