如何解决无法获取数据未处理的拒绝类型错误:无法读取未定义的属性“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;
解决方法
更新
我尝试使用 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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。