6.3 原生节点与延迟挂载
有了 6.2 的 createRoot 和 onCleanup,我们在第四章为了搬运清理函数而发明的 Renderable<{ node, dispose }> 就正式完成了它的历史使命。
这一节我们把职责彻底拆干净:原生 Node 只负责挂到 DOM 哪里,所有权树负责什么时候清理。
为什么 render 要从 render(<App />, app) 改成 render(() => <App />, app)?
先看两行调用的求值顺序差异:
// 旧写法:在进入 render 之前,<App /> 就已经被求值执行完了
render(<App />, app);
// 新写法:render 先建立 createRoot,再在根作用域内调用 () => <App />
render(() => <App />, app);
在 JavaScript 里,函数实参总是在进入函数体之前先求值。如果写成 render(<App />, app),<App /> 里的 createEffect 和 onCleanup 执行时,render 内部的 createRoot 根本还没开始,整棵树的副作用都找不到归属。
把第一个参数改成延迟工厂 view: () => Node 后,一切顺理成章:
- 退掉
Renderable:src/dom.ts收敛为四个核心入口:createText(value)、createReactiveText(getValue)、createElement(tag, props, children)和render(view, container)。JSX.Element直接就是原生Node。 - 去掉元素层手工清理代码:
createElement不再需要维护disposers[]、不再手写递归children.dispose(),也不再套一层元素级try / catch。bindProperty里的createEffect自动归入当前 Owner,onClick的解绑直接写进onCleanup(() => element.removeEventListener("click", handleClick))。 - 自动兜住兄弟节点抛错回滚:遇到
<div><FirstSibling /><BrokenSibling /></div>时,即使BrokenSibling抛错时父元素<div>还没开始构造,FirstSibling已经把自己的订阅和点击监听登记进了render的createRoot,createRoot的catch会立刻把FirstSibling清理干净,彻底填平 5.3 留下的缺口。
flowchart TD
subgraph Old["旧架构(第四、五章)"]
direction LR
O1["每层返回 { node, dispose }"] --> O2["父元素手工收集 disposers[]"] --> O3["无法覆盖兄弟抛错与组件内副作用"]
end
subgraph New["新架构(第六章起)"]
direction LR
N1["render 先建 createRoot"] --> N2["再求值 () => App() 返回原生 Node"] --> N3["effect 与 onCleanup 自动归属根作用域"]
end
Old --> New
为下一节 <Show> 铺路:DocumentFragment 与 try / finally 安全卸载
下一节实现 <Show> 时,一个条件组件可能需要一次性往容器里挂载多个节点(例如两枚注释锚点加中间的真实内容),最自然的返回类型就是原生 DocumentFragment(它本身继承自 Node)。
但 DocumentFragment 有一个著名的 DOM 特性:调用 container.appendChild(fragment) 后,fragment 内部的全部子节点会被搬进 container,而 fragment 自己瞬间变成空的。如果卸载时直接对空的 fragment 调 removeChild,页面上挂载出来的节点一个都移不走。
因此 render 的挂载与卸载还要守住三条边界:
- 挂载前快照子节点:如果
node instanceof DocumentFragment,在container.appendChild(node)之前先把Array.from(node.childNodes)存成mountedNodes;普通节点直接存[node]。 - 用
try / finally兜住 DOM 移除:卸载时把dispose()放进try,把移除mountedNodes的循环放进finally。即使某个用户注册的onCleanup抛错,已挂载的节点依然会从容器移除,不会卡死在页面上。 - 只移除仍属于目标容器的节点:移除前判断
mounted.parentNode === container再调container.removeChild(mounted)。这样既不会误伤容器原有的兄弟节点,也不会把已经被外部代码移到别处的节点强行拆走。
解答 展开
补齐 src/dom.ts 中 render 的 DocumentFragment 子节点快照与 try / finally 安全卸载逻辑:
export function render(view: () => Node, container: Node): Dispose {
return createRoot((dispose) => {
const node = view();
// DocumentFragment 插入后会被清空,必须在 appendChild 前先快照本次要挂载的全部顶层节点。
const mountedNodes = node instanceof DocumentFragment ? Array.from(node.childNodes) : [node];
container.appendChild(node);
let disposed = false;
return () => {
// 卸载保持幂等:先释放所有权树,并在 finally 中只移除仍直接挂在目标容器下的节点。
if (disposed) return;
disposed = true;
try {
dispose();
} finally {
for (const mounted of mountedNodes) {
if (mounted.parentNode === container) {
container.removeChild(mounted);
}
}
}
};
});
}
这里的三道防线缺一不可:
- 插入前快照:
DocumentFragment在container.appendChild(node)后会清空,提前拍下Array.from(node.childNodes)才能记住本次挂载出去的全部顶层节点。 try / finally兜底移除:即使某条onCleanup在dispose()阶段抛错,已挂载到页面的节点依然会被移走,不会滞留成孤儿 DOM。mounted.parentNode === container守卫:只移除仍直接属于目标容器的节点,既不误删容器原有兄弟,也不去动已经被外部迁走的节点。
保存并启用 3 条测试后运行 pnpm format && pnpm check && pnpm test:run && pnpm build,60 条测试和构建全部通过。现在 render 已经完全准备好承接下一节返回 DocumentFragment 的 <Show>。
# 查看 src 目录下从题目到解答的全部改动。
git diff 6.3-learn 6.3-solution -- src