英文:
Is there any trick to make the code only run when hydrating html
问题
- Server-side rendering
- 客户端混合渲染(Client-side Hydrating)
- 普通客户端渲染(Normal client-side rendering)
就像使用 typeof window === 'undefined'
来使代码仅在服务器端运行一样,是否有任何技巧可以使代码仅在第二种情况下运行?
const useSomething = () => {
if (typeof window === 'undefined') {
// 在服务器端渲染时
}
if ( ??? ) {
// 在客户端混合渲染时
}
// 在客户端渲染时
}
英文:
There are three situations when react ssr
- Server-side rendering
- Client-side Hydrating
- Normal client-side rendering
Just like using typeof window === 'undefined'
to make the code run only on the server side, is there any trick to make the code run only on the second situation ?
const useSomething = () => {
if (typeof window === 'undefined') {
// when ssr
}
if ( ??? ) {
// when client-side Hydrating
}
// client-side rendering
}
答案1
得分: 1
在处理React应用中的服务器端渲染(SSR)时,有三种情况(正如您提到的),代码可能会执行:在服务器端渲染期间、在客户端渲染期间以及在正常的客户端渲染期间。
-
在服务器端渲染期间,JavaScript代码在服务器上执行,其中未定义
window
,因此typeof window === 'undefined'
可以用来检测这一情况。 -
当应用加载到客户端时,由服务器生成的HTML在浏览器中呈现,JavaScript代码再次执行。这时,
window
已经被定义,但应用的状态需要通过从服务器传递的数据进行初始化。window.__INITIAL_STATE__
对象包含了从服务器传递的初始状态值。
因此,要检测代码是否在客户端渲染期间运行,您可以检查window.__INITIAL_STATE__
是否被定义。
以下是您可以进行检查的方法:
const useSomething = () => {
if (typeof window === 'undefined') {
// 我们处于服务器端渲染
} else if (window.__INITIAL_STATE__) {
// 我们处于客户端渲染初始化期间
} else {
// 我们处于正常的客户端渲染期间
}
};
英文:
When dealing with SSR in React applications, there are three situations (like you mentioned) where the code can be executed: during server-side rendering, during client-side hydration, and during normal client-side rendering.
-
During server-side rendering, the JavaScript code is executed on the server, where window is not defined, that's why
typeof window === 'undefined'
works to detect that. -
When the application is loaded on the client, the server-generated HTML is rendered in the browser, and the JavaScript code is executed again. This time, window is defined, but the application's state needs to be hydrated with the data passed from the server. The window.INITIAL_STATE object contains the initial state values that were passed from the server.
So, to detect whether the code is running during client-side hydration, you can check if window.INITIAL_STATE is defined.
Here's how you can check for that
const useSomething = () => {
if (typeof window === 'undefined') {
// We're in server-side rendering
} else if (window.__INITIAL_STATE__) {
// We're in client-side hydration
} else {
// We're in normal client-side rendering
}`
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论