[英]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.