【发布时间】:2020-05-26 14:03:15
【问题描述】:
我有一个自定义钩子,它检查窗口宽度以有条件地呈现一些 UI 元素。它在开发期间工作正常,但在 Gatsby 构建时失败。
这是我的钩子的代码:
export const useViewport = () => {
const [width, setWidth] = React.useState(window.innerWidth);
React.useEffect(() => {
const handleWindowResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleWindowResize);
return () => window.removeEventListener("resize", handleWindowResize);
}, []);
// Return the width so we can use it in our components
return { width };
}
然后在我的组件中我这样使用它:
const { width } = useViewport();
const breakpoint = 767
/** in JSX **/
{
width > breakpoint ? <Menu {...props} /> : <Drawer {...props} />
}
根据 Gatsby docs window 在构建过程中不可用。我尝试将if (typeof window !== 'undefined') 条件设置为挂钩,但出现以下错误:
Cannot destructure property 'width' of 'Object(...)(. ..)' as it is undefined
我也尝试将const { width } = useViewport() 包装在React.useEffect 挂钩中,但随后我收到一个错误,即我的JSX 中的width 未定义。
我该如何解决这个问题?
【问题讨论】: