为了账号安全,请及时绑定邮箱和手机立即绑定

如何遍历json api数据对象

如何遍历json api数据对象

白板的微信 2023-05-25 16:29:40
我正在尝试使用天气 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 数据吗?
查看完整描述

2 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

weather您指定的 的默认值是[]:一个空数组。

[].current将是未定义的,因此会出现错误。

要么使用一组更完整的默认数据。或测试是否weather.current具有价值。


查看完整回答
反对 回复 2023-05-25
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

您忘记了您的效果是异步的。


在第一个渲染中,weather将被设置为[],因为这就是useState设置它的原因。您将要在稍后完成的效果排队,然后渲染效果前的元素:


return (

    <div>

      <h1>hello!</h1>

      {console.log(weather.current.temp_c)}

    </div>

  );

由于weather等于[],weather.current是undefined。undefined.temp_c是一个TypeError。


放置在获取数据后console.log运行的代码。


查看完整回答
反对 回复 2023-05-25
  • 2 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信