【问题标题】:how to fix window is not defined in gatsby如何修复窗口未在 gatsby 中定义
【发布时间】:2021-09-30 13:04:26
【问题描述】:

我正在使用 Gatsby 制作应用程序,但出现此错误:

SSRing 路径时出现意外错误:/ ReferenceError: 未定义窗口。

  const activeIndex = () => {
    const found = routes.indexOf(
      routes.filter(
        ({ node: { name, link } }) =>
          (link || `/${name.toLowerCase()}`) ===  window.location.pathname
      )[0]
    )

    return found === -1 ? false : found
  }

错误来自这些代码。谢谢

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

    正如您在docs 中看到的,您只需添加以下条件:

    typeof window !== "undefined"
    

    应用于您的代码:

      const activeIndex = () => {
        if(typeof window != "undefined"){
          const found = routes.indexOf(
            routes.filter(
              ({ node: { name, link } }) =>
                (link || `/${name.toLowerCase()}`) ===  window.location.pathname
            )[0]
          )
    
          return found === -1 ? false : found
        }
      }
    

    【讨论】:

    • 感谢您的回答。现在是固定的,但是当我想走不同的路线时,我遇到了问题。例如:当我点击衬衫,然后联系时,它的 404:localhost:8000/shirts/contact。不直接联系。有什么帮助吗?
    • 这完全是一个全新的不同问题。但是对于您所说的,您正在连接 URL(首先是衬衫,然后是联系,生成 /shirts/contact)。只需在 URL 的开头添加一个斜杠 (/),例如:<Link to="/contact"> 而不是 to="contact"。如果问题已解决,请接受该问题,如果还有更多问题,请打开一个新问题,因为在 2 行描述中很难猜出发生了什么...
    • 对于动态链接,方法完全相同。检查您的链接和蛞蝓的相关性。除了与原始问题无关之外,还应该解决这个问题
    • 再次感谢 Ferran。
    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 2021-06-27
    • 2020-12-30
    • 2021-08-17
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多