简体   繁体   中英

Why window.innerWidth is 'undefined' onComponentMount (React(?

when i first load my app, my width is undefined. It works as expected ONLY after i resize it.

    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])

I am conditionally rendering come components based on width but it doesnt work unless i resize.

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

window does not have innerwidth property.

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

try this, const [width, setWidth] = useState(window.innerWidth);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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