【发布时间】:2021-02-02 14:16:10
【问题描述】:
我正在尝试使用天气 api 获取特定位置的当前温度。我想使用天气 api 的响应并使用 react 存储在 State 中。
我的问题是我在遍历 json 数据时总是出错。
WeatherApp.js:53 Uncaught TypeError: Cannot read property 'temp_c' of undefined
这是我记录到控制台的 json 响应数据。
这里的每个请求都是来自 weather.current 的响应
代码:
import React, { useEffect, useState } from "react";
import Axios from "axios";
function WeatherApp() {
const [weather, setWeather] = useState([]);
useEffect(() => {
async function getWeather() {
Axios.get(
"https://api.weatherapi.com/v1/current.json?key=xxxx&q=40507"
)
.then(response => {
setWeather(response.data);
})
.catch(e => console.log("There was an error that occurred."));
}
getWeather();
}, []);
return (
<div>
<h1>hello!</h1>
{console.log(weather.current.temp_c)}
// I am able to print to the console when i do the following
{console.log(weather.curret)}
</div>
);
}
export default WeatherApp;
我没有正确遍历 json 数据吗?
【问题讨论】:
-
您能否在错误中添加
console.log,以便您有更好的主意。catch(e => console.log(e));并在这里分享结果。 -
嗨,错误不是来自 api 请求。错误来自
{console.log(weather.current.temp_c)} -
尝试在控制台输出
{console.log(weather.current)},看看是否返回任何数据或返回未定义 -
试试
{Object.keys(weather).length > 0 ? console.log(weather.current.temp_c) : ''} -
@KetanRamteke 更新了问题以包含您要求的图像。这很好用。但是,当我执行
{console.log(weather.current.temp_c}时,我收到错误消息
标签: javascript json reactjs api