gpt4 book ai didi

reactjs - ReactDOM.Hydrate() 会触发客户端的生命周期方法吗?

转载 作者:行者123 更新时间:2023-12-03 13:28:54 24 4
gpt4 key购买 nike

来自 React 16 docs关于ReactDOM.Hydrate()

Same as render(), but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer. React will attempt to attach event listeners to the existing markup.

  1. ReactDOM.Hydrate() 还会在客户端触发生命周期方法,例如 componentWillMount()componentDidMount()初始渲染?

  2. 水合期间客户端会调用 render() 方法吗?我想不是,因为这就是 ReactDOM.render()ReactDOM.Hydrate() 之间的区别?

如果客户端不会调用 render 方法,我们就不会期望触发 componentDidMount() 生命周期方法。

如果客户端没有调用任何生命周期方法,我们如何知道 React 何时完成渲染。我认为回调采用以下语法:

ReactDOM.hydrate(element, container[, callback])

我想了解当 React“尝试将事件监听器附加到现有标记”时是否有可用的生命周期方法/ Hook (对应用程序提供更多控制)。

最佳答案

  1. 由于(并且应该)在客户端调用 ReactDOM.Hydrate,那么它应该运行componentDidMount。在服务器上渲染时已经调用了 componentWillMountcomponentDidMount 不在服务器上运行,因此当您调用 Hydro 时,应用程序会运行该事件。

  2. 将水合物视为一种不同的渲染方法。它确实渲染,但不是以同样的方式渲染。它会查找服务器渲染的 React 和客户端 React 之间的不匹配。它不会再次渲染所有内容。

React expects that the rendered content is identical between the server and the client. It can patch up differences in text content (such as timestamps), but you should treat mismatches as bugs and fix them

但是,您可能想做一些疯狂的事情,例如在客户端呈现完全不同的内容(与在服务器上呈现的内容)。为此请注意本段

If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a state variable like this.state.isClient, which you can set to true in componentDidMount(). This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. Note that this approach will make your components slower because they have to render twice, so use it with caution.

正如您所看到的,它执行了渲染过程。如果没有不匹配,React 会为此进行优化。

我希望它能够澄清。我的发言来自于 React SSR 的经验以及对阅读文档的基本理解。

关于reactjs - ReactDOM.Hydrate() 会触发客户端的生命周期方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47202696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com