【问题标题】:TypeError: Cannot read properties of undefined (reading 'country')TypeError:无法读取未定义的属性(读取“国家”)
【发布时间】:2022-01-11 11:09:38
【问题描述】:

我正在尝试从 API 获取数据并在我的应用中使用该数据。但问题是,当我尝试从我刚刚从 API 获得的 JSON 中获取某个对象或数据时,我得到一个 TypeError: Cannot read property 'country' of undefined。 该属性确实存在。 顺便说一句,我正在使用 React.js。 我非常感谢您的帮助和指导。 代码如下:

App.js

{typeof weather != 'undefined' ? (
  <div>
    <div className="location-box">
      <div className="location">
        
        {weather.name},{weather.sys.country} 
      </div>
      <div className="date"> {dateBuilder(new Date())} </div>
    </div>

    <div className="weather-box">
      <div className="weather-temperature">15*C</div>
      <div className="weather">Sunny </div>
    </div>
  </div>
) : ("NULL")}

我们要从中获取数据的 API。

function App() {
  const [query, setQuery] = useState("");
  const [weather, setWeather] = useState({});

  const Search = (evt) => {
    if (evt.key === "Entre") {
      debugger;
      fetch(`${api.base}weather?q=${query}&units=metric&APPID${api.key}`)
        .then((res) => res.json())

        .then((result) => {
          setWeather(result);
          setQuery("");
          console.log(result);
        });
    }
  };
}

【问题讨论】:

  • 该属性不存在,因为最初呈现组件时您没有数据。你有一个空对象。它可能在数据中,但您需要在加载数据后并更新状态。
  • 您能否console.log weather 变量并查看weather.sys 是否真的存在?
  • 好的,我会在控制台查看天气
  • 把这个:{weather.name},{weather.sys?.country}

标签: javascript reactjs react-redux react-hooks


【解决方案1】:

如果您确定该属性确实存在,那么它必须是初始渲染。您用{} 初始化useStaet,但要注意undefined。 所以把useState({})改成useState()

const [weather, setWeather] = useState();

您还可以在阅读country时添加一个空检查。

{weather.name}, {weather.sys?.country}

【讨论】:

    【解决方案2】:

    问题是由于您的天气检查:typeof weather != 'undefined' 而您的天气初始值是{}。为了解决这个问题,不要为天气设置初始值。像这样:

    const [weather, setWeather] = useState();
    

    因此,在第一次渲染中,天气值将是 undefined,在下一次渲染中,它包含您的 api 响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 2021-11-24
      • 2021-12-20
      • 2021-11-27
      • 2022-01-21
      • 2021-12-04
      • 2021-12-09
      • 2021-12-06
      相关资源
      最近更新 更多