关于javascript:React和DOM的那些事节点更新

10次阅读

共计 1631 个字符,预计需要花费 5 分钟才能阅读完成。

点击进入 React 源码调试仓库。

React 的更新最终要落实到页面上,所以本文次要解说 DOM 节点(HostComponent)和文本节点 (HostText) 的更新,对于前者来说更新是 props 的更新,对后者来说更新是文字内容的更新。

commitWork是节点更新的入口。

function commitMutationEffectsImpl(
  fiber: Fiber,
  root: FiberRoot,
  renderPriorityLevel,
) {

  ...

  switch (primaryEffectTag) {

    ...

    case Update: {
      const current = fiber.alternate;
      commitWork(current, fiber);
      break;
    }
  }
}

commitWork 重点解决了 HostComponent 和 HostText。

HostText 的更新

更新 HostText,实际上也就是更新文本内容,过程比较简单,最终调用 commitTextUpdate 来设置文本内容。

function commitWork(current: Fiber | null, finishedWork: Fiber): void {

  ...

  switch (finishedWork.tag) {
    ...
    case HostText: {
      const textInstance: TextInstance = finishedWork.stateNode;
      const newText: string = finishedWork.memoizedProps;
      const oldText: string =
        current !== null ? current.memoizedProps : newText;
      commitTextUpdate(textInstance, oldText, newText);
      return;
    }
  }
  ...
}

HostComponent 的更新

更新 HostComponent 是更新 fiber 节点上的 props,这须要应用到在 render 阶段的 complete 过程中节点 props 的 diff 后果:fiber.updateQueue。再来回顾一下它的模式:数组,以 2 为单位,index 为偶数的是 key,为奇数的是 value。

['style', { color: 'blue'}, title, '测试题目' ]

整个更新过程就是遍历数组,最终调用 updateDOMProperties 将属性和值设置到 DOM 节点上。

function updateDOMProperties(
  domElement: Element,
  updatePayload: Array<any>,
  wasCustomComponentTag: boolean,
  isCustomComponentTag: boolean,
): void {
  // 遍历 updateQueue 数组,利用更新
  for (let i = 0; i < updatePayload.length; i += 2) {const propKey = updatePayload[i];
    const propValue = updatePayload[i + 1];
    if (propKey === STYLE) {setValueForStyles(domElement, propValue);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {setInnerHTML(domElement, propValue);
    } else if (propKey === CHILDREN) {setTextContent(domElement, propValue);
    } else {setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
    }
  }
}

总结

整个节点的更新过程比拟单纯,将新的属性值或者新的文本内容设置到节点上,并不波及其余简单的操作,比拟好了解。

欢送扫码关注公众号,发现更多技术文章

正文完
 0