Skip to content

Commit

Permalink
五: 2.创建 reconciler
Browse files Browse the repository at this point in the history
  • Loading branch information
zh-lx committed Nov 10, 2021
1 parent 50a52fb commit 7eebaac
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 23 deletions.
25 changes: 2 additions & 23 deletions 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 树
Expand Down Expand Up @@ -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);
}

// 设置下一个工作单元
Expand Down
24 changes: 24 additions & 0 deletions 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++;
}
}

0 comments on commit 7eebaac

Please sign in to comment.