【发布时间】:2021-12-29 13:01:21
【问题描述】:
假设我有基于window.innerWidth 的响应式样式的服务器端渲染应用程序,如何在index.html 的初始GET 请求中传递客户端的屏幕尺寸,以便我可以在服务器上进行准备并以适当样式的页面进行响应?
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)一无所知,并且很可能,<p> 的相应部分将留空,直到响应启动客户端,触发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