簡體   English   中英

NextJS:如何讓這個組件在頁面加載時顯示寬度?

[英]NextJS: How do I get this component to display width on page load?

當運行以下獲取瀏覽器屏幕寬度的代碼時,出現此錯誤:

ReferenceError: window 未定義

注釋掉的代碼有效,使用 0 作為默認值,但在瀏覽器寬度更改時會正確更新。

我要么得到 window 未定義錯誤,要么將默認數字傳遞給 state,這會在頁面加載時顯示不正確的寬度。

如何在頁面加載時定義 window.innerWidth?

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

const WindowTracker = () => {
    const [show, setShow] = useState(true);
    // const [windowWidth, setWindowWidth] = useState(0);
    const [windowWidth, setWindowWidth] = useState(window.innerWidth);

    const triggerToggle = () => {
        setShow(!show);
    };

    useEffect(() => {
        function watchWidth() {
            setWindowWidth(window.innerWidth);
        }

        window.addEventListener("resize", watchWidth);

        return function () {
            window.removeEventListener("resize", watchWidth);
        };
    }, []);

    return (
        <div>
            <button onClick={triggerToggle}>Toggle WindowTracker</button>
            {show && <h1>Window width: {windowWidth}px</h1>}
        </div>
    );
    // }
};

export default WindowTracker;

謝謝!

使用這個鈎子:

 const [windowWidth, setWindowWidth] = useState(); useEffect(() => { setWindowWidth(window.innerWidth) }, [window.innerWidth])

發生這種情況是因為在 nextjs 在 window 服務器上執行的預渲染中它尚未定義,我通過添加一個 if 在我的代碼中解決了這個問題,這是它看起來如何的示例代碼

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

const WindowTracker = () => {
  const [show, setShow] = useState(true);
  // const [windowWidth, setWindowWidth] = useState(0);
  const [windowWidth, setWindowWidth] = useState(typeof window !== "undefined" ? window.innerWidth : 0);

  const triggerToggle = () => {
    setShow(!show);
  };

  useEffect(() => {
    if (typeof window !== "undefined") {
      function watchWidth() {
        setWindowWidth(window.innerWidth);
      }

      window.addEventListener("resize", watchWidth);

      return function () {
        window.removeEventListener("resize", watchWidth);
      };
    }
  }, []);

  return (
    <div>
      <button onClick={triggerToggle}>Toggle WindowTracker</button>
      {show && <h1>Window width: {windowWidth}px</h1>}
    </div>
  );
  // }
};

export default WindowTracker;

您應該在組件掛載時觸發setWindowWidth

const isClientSide = () => typeof window !== 'undefined';

const getWindowSize = () => {
    if (isClientSide()) return window.innerWidth
    return 0
}

const WindowTracker = () => {
    const [show, setShow] = useState(true);
    const [windowWidth, setWindowWidth] = useState(getWindowSize());

    const triggerToggle = () => {
        setShow(!show);
    };

    useEffect(() => {
        function watchWidth() {
            setWindowWidth(window.innerWidth);
        }

        window.addEventListener("resize", watchWidth);
        setWindowSize(getWindowSize());  <=== This should set the right width
        return function () {
            window.removeEventListener("resize", watchWidth);
        };
    }, []);

    return (
        <div>
            <button onClick={triggerToggle}>Toggle WindowTracker</button>
            {show && <h1>Window width: {windowWidth}px</h1>}
        </div>
    );
};

export default WindowTracker;

useEffect掛鈎中,您還可以調用setWindowWidth(window.innerWidth); at 將 state 和 window.innerWidth 設置為在 pageLoad 上具有所需的寬度。

const [windowWidth, setWindowWidth] = useState(0);

useEffect(() => {
        function watchWidth() {
            setWindowWidth(window.innerWidth);
        }

        window.addEventListener("resize", watchWidth);

        //  Call right away so state gets updated with initial window size
        setWindowWidth(window.innerWidth);

        return function () {
            window.removeEventListener("resize", watchWidth);
        };
    }, []);

暫無
暫無

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

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