【问题标题】:Pass window.innderWidth in initial GET request在初始 GET 请求中传递 window.innerWidth
【发布时间】:2021-12-29 13:01:21
【问题描述】:

假设我有基于window.innerWidth 的响应式样式的服务器端渲染应用程序,如何在index.html 的初始GET 请求中传递客户端的屏幕尺寸,以便我可以在服务器上进行准备并以适当样式的页面进行响应?

考虑following example

import React, { useState, useEffect } from 'react';

export const App = () => {
  const [width, setWidth] = useState(globalThis?.innerWidth);

  useEffect(() => {
    const updateWidth = () => setWidth(window.innerWidth);

    window.addEventListener('resize', updateWidth);

    return () => window.removeEventListener('resize', updateWidth);
  });

  return <p>Your window is {width}px wide</p>;
};

虽然服务器正在为上述组件呈现 html,但它对 .innerWidth(因此,width)一无所知,并且很可能,&lt;p&gt; 的相应部分将留空,直到响应启动客户端,触发useState() 并使用globalThis 启动width(= window 现在).innerWidth

所以,我的意思是如何在我的 GET 请求中传递window.innerWidth(显然,哪个浏览器知道它何时请求 index.js),以便我可以在服务器端使用它,例如与:

export function getServerSidePorps(context) {

  // some logic here, extracting window width from context.req

  return {
    props: {width},
  };
}

【问题讨论】:

  • 那么发送标头以及您为获取内容而进行的 fetch 调用?

标签: html reactjs next.js server-side-rendering


【解决方案1】:

你不能这样做,因为浏览器宽度只存在于客户端。在渲染页面之前,不可能在服务器端使用它。

【讨论】:

  • 因为服务器端显然没有window,所以也不可能有window.innerWidth。我知道这一点,我并没有尝试使用它。我想弄清楚的是略有不同:当浏览器从服务器请求 index.html 时,它已经知道它可以使用哪个屏幕,所以如果浏览器可以给出一个关于它的 hint (使用 HTTP -header 或查询参数,无论如何)到服务器,后者可以准备适当的 html。
猜你喜欢
  • 1970-01-01
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2022-11-14
  • 2019-06-07
  • 2020-08-06
相关资源
最近更新 更多