首页 > 解决方案 > 无法获取数据。未处理的拒绝(TypeError):无法读取未定义的属性“0”

问题描述

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

未处理的拒绝(TypeError):无法读取未定义的属性“0”

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;

标签: javascriptreactjsapiopenweathermapweather-api

解决方案


更新

我尝试使用 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);
}

};


推荐阅读