[英]Window is undefined in Nextjs but values are needed in useState
Trying to get the exact window values as the screen size changes.随着屏幕尺寸的变化,试图获得准确的 window 值。 How can i get the window values into useState()?如何将 window 值放入 useState()? Since useState cannot be used in a conditional, and window is undefined outside a useEffect?由于 useState 不能在条件中使用,并且 window 在 useEffect 之外未定义?
const isSSR = typeof window !== "undefined";
const [windowSize, setWindowSize] = React.useState({
width: isSSR ? 1200 : window.innerWidth,
height: isSSR ? 800 : window.innerHeight,
});
function changeWindowSize() {
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
}
React.useEffect(() => {
window.addEventListener("resize", changeWindowSize);
return () => {
window.removeEventListener("resize", changeWindowSize);
};
}, []);
return windowSize;
}
Two things to be corrected,有两点需要纠正
isSSR
logic is not right.您的isSSR
逻辑不正确。 due to that, window.innerWidth
and window.innerHeight
were evaluated in the server.因此,在服务器中评估了window.innerWidth
和window.innerHeight
。 It should be ===
not !==
.它应该是===
而不是!==
。const isSSR = typeof window === "undefined";
function changeWindowSize() {
if(!isSSR){
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
}
}
*** changeWindowSize
change is not needed since you call it only within a useEffect
and useEffect
hook is not executed in the server. *** changeWindowSize
更改,因为您仅在useEffect
中调用它,并且useEffect
挂钩不会在服务器中执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.