[ReactDOM] Client API:hydrateRoot #75
kiinlam
started this conversation in
[04] React
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
hydrateRoot
用于将 React 连接到由 RSC 渲染的现有 HTML 中。此过程称为 hydrate。使用
调用
hydrateRoot
将连接到指定的 DOM 元素domNode
,并以此为根节点,接管并控制其中的 DOM 树。reactNode
是由 RSC 通过服务端 API 渲染并传输的,如renderToPipeableStream(<App />)
。hydrateRoot
返回的根节点root
是一个带有两个方法的对象:root.render(reactNode)
:用于更新 hydrate 根节点。root.unmount()
:用于销毁 React 根节点。可通过
options
选项配置新创建的根节点:onRecoverableError
:可选的回调函数,在 React 从异常错误中恢复时自动调用。identifierPrefix
:可选的 id 前缀,通过useId()
生成,避免同一个页面下的多个根节点出现 id 冲突。root.render(reactNode)
更新一个 hydrate 根组件中的 React 节点来渲染浏览器端 DOM 元素。
root.render
,React 将清除现有的服务端渲染 HTML 内容,并将整个根节点切换到客户端渲染。通常情况下,并不需要调用
root.render
,hydrate 过程已经渲染了 React 节点。root.unmount()
销毁 React 根节点中的一个已经渲染的树,所有事件处理程序以及组件树上的状态将被移除,同时清空根节点下所有 HTML。
当 React 根节点控制的 DOM 被 React 以外的代码删除时,需要调用
root.unmount
来通知 React 停止控制已经被移除的根节点的内容。否则,其内部组件将不能及时释放消息订阅等资源。提示
只有应用程序的 HTML 是由 RSC 生成的,才需要在客户端上调用
hydrateRoot
进行 hydrate,否则应该调用createRoot
。Beta Was this translation helpful? Give feedback.
All reactions