【问题标题】:Gatsby build fails because window is undefined in a React hookGatsby 构建失败,因为在 React 挂钩中未定义窗口
【发布时间】: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 未定义。

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

    看几个solutions here

    特别是这个:

    您需要自行调整挂钩。在外部范围内定义默认值并将它们用作默认状态应该可以解决问题:

    【讨论】:

      【解决方案2】:

      参加聚会有点晚了,但在寻找其他东西时看到了这个。 Window 在 SSR/SSG 期间不可用,因此您需要将 window 的任何用法包含在 iffy 中。

      if (typeof window !== 'undefined') {
        // Do what you need with any calls to window
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        • 1970-01-01
        相关资源
        最近更新 更多