Skip to content

Commit 7eebaac

Browse files
committed
五: 2.创建 reconciler
1 parent 50a52fb commit 7eebaac

File tree

2 files changed

+26
-23
lines changed

2 files changed

+26
-23
lines changed

src/mini-react/fiber.js

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { renderDom } from './react-dom';
22
import { commitRoot } from './commit';
3+
import { reconcileChildren } from './reconciler';
34

45
let nextUnitOfWork = null;
56
let workInProgressRoot = null; // 当前工作的 fiber 树
@@ -49,29 +50,7 @@ function performUnitOfWork(workInProgress) {
4950
let elements = Array.isArray(children) ? children : [children];
5051
// 打平列表渲染时二维数组的情况(暂不考虑三维及以上数组的情形)
5152
elements = elements.flat();
52-
53-
let index = 0; // 当前遍历的子元素在父节点下的下标
54-
let prevSibling = null; // 记录上一个兄弟节点
55-
56-
while (index < elements.length) {
57-
// 遍历子元素
58-
const element = elements[index];
59-
// 创建新的 fiber
60-
const newFiber = {
61-
element,
62-
return: workInProgress,
63-
stateNode: null,
64-
};
65-
if (index === 0) {
66-
// 如果下标为 0,则将当前fiber设置为父 fiber 的 child
67-
workInProgress.child = newFiber;
68-
} else {
69-
// 否则通过 sibling 作为兄弟 fiber 连接
70-
prevSibling.sibling = newFiber;
71-
}
72-
prevSibling = newFiber;
73-
index++;
74-
}
53+
reconcileChildren(workInProgress, elements);
7554
}
7655

7756
// 设置下一个工作单元

src/mini-react/reconciler.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export function reconcileChildren(workInProgress, elements) {
2+
let index = 0; // 当前遍历的子元素在父节点下的下标
3+
let prevSibling = null; // 记录上一个兄弟节点
4+
5+
while (index < elements.length) {
6+
// 遍历子元素
7+
const element = elements[index];
8+
// 创建新的 fiber
9+
const newFiber = {
10+
element,
11+
return: workInProgress,
12+
stateNode: null,
13+
};
14+
if (index === 0) {
15+
// 如果下标为 0,则将当前fiber设置为父 fiber 的 child
16+
workInProgress.child = newFiber;
17+
} else {
18+
// 否则通过 sibling 作为兄弟 fiber 连接
19+
prevSibling.sibling = newFiber;
20+
}
21+
prevSibling = newFiber;
22+
index++;
23+
}
24+
}

0 commit comments

Comments
 (0)