Skip to content

Commit 59ffd50

Browse files
committed
✨feat: 完善9.1减少DOM操作的性能开销
1 parent 741d9aa commit 59ffd50

File tree

1 file changed

+32
-18
lines changed

1 file changed

+32
-18
lines changed

第9章简单Diff算法/9.1_减少DOM操作的性能开销.html

+32-18
Original file line numberDiff line numberDiff line change
@@ -48,36 +48,50 @@
4848
}
4949

5050
function patchChildren (n1, n2, container) {
51+
// 如果新虚拟节点的子节点是文本节点
5152
if (typeof n2.children === 'string') {
53+
// 如果旧虚拟节点的子节点是数组,表示之前是多个子节点,需要将其全部移除
5254
if (Array.isArray(n1.children)) {
53-
n1.children.forEach((c) => unmount(c))
55+
n1.children.forEach((c) => unmount(c));
5456
}
55-
setElementText(container, n2.children)
56-
} else if (Array.isArray(n2.children)) {
57-
const oldChildren = n1.children
58-
const newChildren = n2.children
59-
const oldLen = oldChildren.length
60-
const newLen = newChildren.length
61-
const commonLength = Math.min(oldLen, newLen)
57+
// 更新容器中的文本内容为新的子节点文本内容
58+
setElementText(container, n2.children);
59+
}
60+
// 如果新虚拟节点的子节点是数组
61+
else if (Array.isArray(n2.children)) {
62+
const oldChildren = n1.children; // 旧子节点数组
63+
const newChildren = n2.children; // 新子节点数组
64+
const oldLen = oldChildren.length; // 旧子节点数组长度
65+
const newLen = newChildren.length; // 新子节点数组长度
66+
const commonLength = Math.min(oldLen, newLen); // 计算公共部分的长度,即两个数组共同的部分
67+
// 循环遍历公共部分的子节点,逐个进行更新
6268
for (let i = 0;i < commonLength;i++) {
63-
patch(oldChildren[i], newChildren[i])
69+
patch(oldChildren[i], newChildren[i]);
6470
}
65-
// 如果 nextLen > prevLen,将多出来的元素添加
71+
// 如果新子节点数组的长度大于旧子节点数组的长度,表示有新增的子节点
6672
if (newLen > oldLen) {
73+
// 遍历新增的子节点,逐个进行挂载
6774
for (let i = commonLength;i < newLen;i++) {
68-
patch(null, newChildren[i], container)
75+
patch(null, newChildren[i], container);
6976
}
70-
} else if (oldLen > newLen) {
71-
// 如果 prevLen > nextLen,将多出来的元素移除
77+
}
78+
// 如果旧子节点数组的长度大于新子节点数组的长度,表示有移除的子节点
79+
else if (oldLen > newLen) {
80+
// 遍历移除的子节点,逐个进行卸载
7281
for (let i = commonLength;i < oldLen;i++) {
73-
unmount(oldChildren[i])
82+
unmount(oldChildren[i]);
7483
}
7584
}
76-
} else {
85+
}
86+
// 如果新虚拟节点的子节点不是文本节点也不是数组,表示是单个子节点
87+
else {
88+
// 如果旧虚拟节点的子节点是数组,表示之前是多个子节点,需要将其全部移除
7789
if (Array.isArray(n1.children)) {
78-
n1.children.forEach(c => unmount(c))
79-
} else if (typeof n1.children === 'string') {
80-
setElementText(container, '')
90+
n1.children.forEach(c => unmount(c));
91+
}
92+
// 如果旧虚拟节点的子节点是文本节点,需要清空容器中的文本内容
93+
else if (typeof n1.children === 'string') {
94+
setElementText(container, '');
8195
}
8296
}
8397
}

0 commit comments

Comments
 (0)