我正在使用异步来获取数据。它已成功加载,但是当我在输入字段中键入新值或刷新页面时,出现以下错误,即无法读取未定义的属性“0”
<块引用>未处理的拒绝(类型错误):无法读取未定义的属性“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;
答案 0 :(得分:0)
更新
我尝试使用 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);
}
};
答案 1 :(得分:0)
有时 API 响应只是“对象”而不是“对象数组”。请先确定您的 API 响应。
在这种情况下,他的解决方案可能是:setWeather(res.weather.main);
代替:setWeather(res.weather[0].main);