简体   繁体   English

Window 在 Nextjs 中未定义,但在 useState 中需要值

[英]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,有两点需要纠正

  1. Your isSSR logic is not right.您的isSSR逻辑不正确。 due to that, window.innerWidth and window.innerHeight were evaluated in the server.因此,在服务器中评估了window.innerWidthwindow.innerHeight It should be === not !== .它应该是===而不是!==
const isSSR = typeof window === "undefined";
  1. And change the client-side function to be safe like below.并将客户端 function 更改为安全,如下所示。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM