只在HTML被渲染时运行代码时有什么窍门吗?

huangapple go评论53阅读模式
英文:

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)时,有三种情况(正如您提到的),代码可能会执行:在服务器端渲染期间、在客户端渲染期间以及在正常的客户端渲染期间。

  1. 在服务器端渲染期间,JavaScript代码在服务器上执行,其中未定义window,因此typeof window === 'undefined'可以用来检测这一情况。

  2. 当应用加载到客户端时,由服务器生成的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.

  1. 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.

  2. 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
  }`
};

huangapple
  • 本文由 发表于 2023年3月4日 09:49:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75633186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定