簡體   English   中英

ReferenceError: window is not defined NextJS

[英]ReferenceError: window is not defined NextJS

在為生產構建應用程序時出現錯誤。 它一直說ReferenceError: window is not defined 我迷失了解決問題

全碼:

const [windowSize, setWindowSize] = useState<WindowInfo>({
        width: window.innerWidth,
        height: window.innerHeight,
    });

    useEffect(() => {
        if (typeof window !== "undefined") { // error showing in this line
            function handleResize() {
                const data: WindowInfo = {
                    width: window.innerWidth,
                    height: window.innerHeight,
                }

                setWindowSize(data);
            }

            window.addEventListener("resize", handleResize);

            handleResize();

            return () => window.removeEventListener("resize", handleResize);
        }
    }, []);

任何人都可以告訴我這個問題的解決方法

window僅是瀏覽器。 在 NodeJS 服務器上,不會定義window

您已經在useEffect內部處理了這個問題,但不是在useState中。 你需要這樣的東西:

const isBrowser = (typeof window !== "undefined");
const [windowSize, setWindowSize] = useState<WindowInfo>({
    width: isBrowser ? window.innerWidth : 0,
    height: isBrowser ? window.innerHeight : 0,
});

我在上面使用 0 作為默認值,但您可以使用對您的項目有意義的任何值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM