无法获取数据。未处理的拒绝 (TypeError):无法读取未定义的 属性 '0'

unable to fetch data. Unhandled Rejection (TypeError): Cannot read property '0' of undefined

我正在使用异步来获取数据。它已成功加载,但是当我在输入字段中键入新值或刷新页面时。我收到以下错误,无法读取未定义的 属性 '0'

Unhandled Rejection (TypeError): Cannot read property '0' of undefined

import React, { useEffect, useState } from "react";
import { API } from "../api";

const Weather = () => {
  const [city, setCity] = useState("");
  const [search, setSearch] = useState("Mumbai");
  const [wind, setWind] = useState("");
  const [weather, setWeather] = useState([]);

  const fetchApi = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid={key}`;
    const response = await fetch(url);
    const res = await response.json();
    setCity(res.main);
    setWeather(res.weather[0].main);
  };

  useEffect(() => {
    fetchApi();
  }, [search]);

  return (
    <div className="container col-md-6 ">
      <div className="card rounded">
        <div className="card-body">
          <input
            type="search"
            className=" searchbox offset-md-3 col-md-6"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
            }}
          />
          {!city ? (
            <>
              <p className="text-center mt-3">No city found</p>
            </>
          ) : (
            <div className="info text-center mt-3">
              <h1 className="mr-2">
                <i className="fas fa-street-view "></i>
              </h1>
              <h2>{search}</h2>
              <h6>{Date()}</h6>

              <span className="row"></span>
              <h3>{city.temp}°C</h3>

              <h5 className="min_max text-danger">
                Humidity:{city.humidity} | Min :{city.temp_min} | Max:{" "}
                {city.temp_max}
              </h5>
              <h1>{weather}</h1>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Weather;

更新

我尝试使用 try 和 catch 块。如果可能发生错误,它将被记录到控制台并且它工作正常

const fetchApi = async () => {
try {
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid={key}`;
  const response = await fetch(url);
  const res = await response.json();
  setCity(res.main);
  setWeather(res.weather[0].main);
  setWind(res.wind);
} catch (err) {
  console.log(err);
}

};

有时 API 响应只是一个“对象”,而不是“对象数组”。请先确定您的 API 回复。

在那种情况下,他的解决方案可能是:setWeather(res.weather.main);

而不是:setWeather(res.weather[0].main);