【问题标题】:Error when building Gatsby website: window is not defined构建 Gatsby 网站时出错:未定义窗口
【发布时间】:2021-06-04 21:54:32
【问题描述】:

我在“gatsby 构建”这个网站时遇到问题,这是我认为唯一使用过窗口的地方,并且不断收到此错误。有什么解决方法可以解决这个问题吗?在 gatsy 中,一切都很好。 我的代码是:

import React, { useState, useEffect } from "react";
import styled from "styled-components";
import { tooltipData, burgerData } from "../../data/menuData";
import MenuButton from "../buttons/MenuButton";

export default function MenuTooltip(props) {
  const { isOpen } = props;

  if (window.innerWidth <= 768) {
    return (
      <Wrapper isOpen={isOpen}>
        {burgerData.map((item, index) => (
          <MenuButton item={item} key={index} />
        ))}
      </Wrapper>
    );
  } else {
    return (
      <Wrapper isOpen={isOpen}>
        {tooltipData.map((item, index) => (
          <MenuButton item={item} key={index} />
        ))}
      </Wrapper>
    );
  }
}

【问题讨论】:

标签: reactjs gatsby


【解决方案1】:

当然有解决方法。只需将您的条件包装在:

  if(typeof window !== 'undefined'){
    if (window.innerWidth <= 768) {
      return (
        <Wrapper isOpen={isOpen}>
          {burgerData.map((item, index) => (
            <MenuButton item={item} key={index} />
          ))}
        </Wrapper>
      );
    } else {
      return (
        <Wrapper isOpen={isOpen}>
          {tooltipData.map((item, index) => (
            <MenuButton item={item} key={index} />
          ))}
        </Wrapper>
      );
    }
  else return null
  }

正如您在docs 中看到的,建议的解决方法是将窗口使用情况包装在typeof window !== 'undefined' 条件中。本质上,这是因为gatsby build 出现在服务器中,而在gatsby develop 中没有window(或其他全局对象,例如document,因为它们尚未创建)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2021-08-16
    • 2020-11-26
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    相关资源
    最近更新 更多