[英]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 />
}
</>
)
innerwidth
屬性。 const [width, setWidth] = useState(window.innerwidth);
❌
const [width, setWidth] = useState(window.innerWidth);
✅
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.