簡體   English   中英

為什么 window.innerWidth 在ComponentMount(React(?

[英]Why window.innerWidth is 'undefined' onComponentMount (React(?

當我第一次加載我的應用程序時,我的width是未定義的。 只有在我調整大小后它才能按預期工作。

    const [width, setWidth] = useState(window.innerwidth);
    useEffect(() => {
        const handleResizeWindow = () => setWidth(window.innerWidth);
        // subscribe to window resize event "onComponentDidMount"
        window.addEventListener("resize", handleResizeWindow);
        return () => {
            // unsubscribe "onComponentDestroy"
            window.removeEventListener("resize", handleResizeWindow);
        };
    }, [])
    useEffect(() => {
        if (width >= 900) {
            dispatch(setView('trip'))
        }
        console.log(width) //prints 'undefined' on initial mount
    }, [width])

我有條件地根據width渲染組件,但除非我調整大小,否則它不起作用。

return
  (
    <>
      {width < 900 &&
         <MobileNavbar />
      }
    </>
  )

window 沒有innerwidth屬性。

const [width, setWidth] = useState(window.innerwidth);

試試這個, const [width, setWidth] = useState(window.innerWidth);

暫無
暫無

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

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