美文网首页
React 18 源代码学习 10 HostComponent

React 18 源代码学习 10 HostComponent

作者: 吴摩西 | 来源:发表于2022-09-09 19:57 被阅读0次

updateHostComponent
如 div, span 等 element 都是 fiber{tag=HostComponent(5)},使用 updateHostComponent 初始化,初始化时几乎没有其他操作,直接 reconcileChildren

当页面初始化时,与 fiber{tag=HostRoot(3)} 不同,进入 workLoopSync 时,fiber{tag=HostRoot(3)} 已经有对应的 currentdiv 对应的 fiber 节点尚未初始化,在 reconcileChildren 中,执行的是
workInProgress.child = mountChildFibers,而不是 workInProgress.child = reconcileChildFibers

再跟踪代码会发现有

// This wrapper function exists because I expect to clone the code in each path
// to be able to optimize each path individually by branching early. This needs
// a compiler or we can do it manually. Helpers that don't need this branching
// live outside of this function.
function ChildReconciler(shouldTrackSideEffects) {
  ...
  return reconcileChildFibers;
}
var reconcileChildFibers = ChildReconciler(true);
var mountChildFibers = ChildReconciler(false);

比较浅显的理解是,在 reconcileChildren 中创建 fiber 时,如果是第一次创建,就无需 shouldTrackSideEffects,后续更新时,则需要 shouldTrackSideEffects,即第一次创建 fiber tree 时,是全量更新,无需记录 side effects,后续更新时,不是全量更新,所以需要记录 side effects。

本例中,此 fiber{tag=HostComponent(5)} 有两个 children,所以会进入 reconcileChildrenArray

reconcileChildrenArray
进入此方法后,首先会先检查每个 child 的 key 是否合法,主要是检查 key 是否有缺少或者相同。然后会给所有的 child 初始化 fiber 并生成初始化的 child, sibling, return 关系。不过 fiber 的实际内容尚未初始化(例如 function 尚未调用)。

随后在 reconcileChildrenworkInProgress.child 返回。

相关文章

网友评论

      本文标题:React 18 源代码学习 10 HostComponent

      本文链接:https://www.haomeiwen.com/subject/bnrznrtx.html