|
48 | 48 | }
|
49 | 49 |
|
50 | 50 | function patchChildren (n1, n2, container) {
|
| 51 | + // 如果新虚拟节点的子节点是文本节点 |
51 | 52 | if (typeof n2.children === 'string') {
|
| 53 | + // 如果旧虚拟节点的子节点是数组,表示之前是多个子节点,需要将其全部移除 |
52 | 54 | if (Array.isArray(n1.children)) {
|
53 |
| - n1.children.forEach((c) => unmount(c)) |
| 55 | + n1.children.forEach((c) => unmount(c)); |
54 | 56 | }
|
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 | + // 循环遍历公共部分的子节点,逐个进行更新 |
62 | 68 | for (let i = 0;i < commonLength;i++) {
|
63 |
| - patch(oldChildren[i], newChildren[i]) |
| 69 | + patch(oldChildren[i], newChildren[i]); |
64 | 70 | }
|
65 |
| - // 如果 nextLen > prevLen,将多出来的元素添加 |
| 71 | + // 如果新子节点数组的长度大于旧子节点数组的长度,表示有新增的子节点 |
66 | 72 | if (newLen > oldLen) {
|
| 73 | + // 遍历新增的子节点,逐个进行挂载 |
67 | 74 | for (let i = commonLength;i < newLen;i++) {
|
68 |
| - patch(null, newChildren[i], container) |
| 75 | + patch(null, newChildren[i], container); |
69 | 76 | }
|
70 |
| - } else if (oldLen > newLen) { |
71 |
| - // 如果 prevLen > nextLen,将多出来的元素移除 |
| 77 | + } |
| 78 | + // 如果旧子节点数组的长度大于新子节点数组的长度,表示有移除的子节点 |
| 79 | + else if (oldLen > newLen) { |
| 80 | + // 遍历移除的子节点,逐个进行卸载 |
72 | 81 | for (let i = commonLength;i < oldLen;i++) {
|
73 |
| - unmount(oldChildren[i]) |
| 82 | + unmount(oldChildren[i]); |
74 | 83 | }
|
75 | 84 | }
|
76 |
| - } else { |
| 85 | + } |
| 86 | + // 如果新虚拟节点的子节点不是文本节点也不是数组,表示是单个子节点 |
| 87 | + else { |
| 88 | + // 如果旧虚拟节点的子节点是数组,表示之前是多个子节点,需要将其全部移除 |
77 | 89 | 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, ''); |
81 | 95 | }
|
82 | 96 | }
|
83 | 97 | }
|
|
0 commit comments