javascript - 无法获取数据。未处理的拒绝(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;
解决方案
更新
我尝试使用 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);
}
};
推荐阅读
- java - Quarkus:当与带有消息签名的处理器方法一起使用时,忽略响应式消息传递的失败策略会引发 CIRCULAR REFERENCE 错误
- json - 在 clasp.json 中设置 rootDir 后,使用 clasp.push 推送谷歌应用脚本失败
- logic - IFTTT 是生产系统还是只是一些规则
- mysql - 如何根据来自其他几个表的数据的聚合选择来选择连接表中的条目?
- python - 在每行中查找最大值的列和行名称
- c# - 另一个表单中的 C# 访问类型
- prolog - 计算序言谓词的句法复杂度
- firebase - Firebase (Flutter) - 尝试通过 getDownloadUrl() 访问云存储上的资源时应用检查失败
- python-3.x - 用户在电报机器人手机中接收后自动全屏显示照片
- regex - 将变量过滤到特定部分/字符 | 从过滤的文本中自动设置分辨率 | Ubuntu,重击