From 7eebaac428789ea2048c92661636378d686b42c7 Mon Sep 17 00:00:00 2001 From: zh-lx <18366276315@163.com> Date: Mon, 8 Nov 2021 09:24:09 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=94:=202.=E5=88=9B=E5=BB=BA=20reconciler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/mini-react/fiber.js | 25 ++----------------------- src/mini-react/reconciler.js | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 23 deletions(-) create mode 100644 src/mini-react/reconciler.js diff --git a/src/mini-react/fiber.js b/src/mini-react/fiber.js index 49642cd..5da692f 100644 --- a/src/mini-react/fiber.js +++ b/src/mini-react/fiber.js @@ -1,5 +1,6 @@ import { renderDom } from './react-dom'; import { commitRoot } from './commit'; +import { reconcileChildren } from './reconciler'; let nextUnitOfWork = null; let workInProgressRoot = null; // 当前工作的 fiber 树 @@ -49,29 +50,7 @@ function performUnitOfWork(workInProgress) { let elements = Array.isArray(children) ? children : [children]; // 打平列表渲染时二维数组的情况(暂不考虑三维及以上数组的情形) elements = elements.flat(); - - let index = 0; // 当前遍历的子元素在父节点下的下标 - let prevSibling = null; // 记录上一个兄弟节点 - - while (index < elements.length) { - // 遍历子元素 - const element = elements[index]; - // 创建新的 fiber - const newFiber = { - element, - return: workInProgress, - stateNode: null, - }; - if (index === 0) { - // 如果下标为 0,则将当前fiber设置为父 fiber 的 child - workInProgress.child = newFiber; - } else { - // 否则通过 sibling 作为兄弟 fiber 连接 - prevSibling.sibling = newFiber; - } - prevSibling = newFiber; - index++; - } + reconcileChildren(workInProgress, elements); } // 设置下一个工作单元 diff --git a/src/mini-react/reconciler.js b/src/mini-react/reconciler.js new file mode 100644 index 0000000..bf96d7c --- /dev/null +++ b/src/mini-react/reconciler.js @@ -0,0 +1,24 @@ +export function reconcileChildren(workInProgress, elements) { + let index = 0; // 当前遍历的子元素在父节点下的下标 + let prevSibling = null; // 记录上一个兄弟节点 + + while (index < elements.length) { + // 遍历子元素 + const element = elements[index]; + // 创建新的 fiber + const newFiber = { + element, + return: workInProgress, + stateNode: null, + }; + if (index === 0) { + // 如果下标为 0,则将当前fiber设置为父 fiber 的 child + workInProgress.child = newFiber; + } else { + // 否则通过 sibling 作为兄弟 fiber 连接 + prevSibling.sibling = newFiber; + } + prevSibling = newFiber; + index++; + } +}