【问题标题】:how to traverse json api data object如何遍历json api数据对象
【发布时间】: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 =&gt; console.log(e)); 并在这里分享结果。
  • 嗨,错误不是来自 api 请求。错误来自{console.log(weather.current.temp_c)}
  • 尝试在控制台输出{console.log(weather.current)},看看是否返回任何数据或返回未定义
  • 试试{Object.keys(weather).length &gt; 0 ? console.log(weather.current.temp_c) : ''}
  • @KetanRamteke 更新了问题以包含您要求的图像。这很好用。但是,当我执行 {console.log(weather.current.temp_c} 时,我收到错误消息

标签: javascript json reactjs api


【解决方案1】:

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

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

要么使用更完整的默认数据集。或者测试weather.current是否有值。

【讨论】:

  • weather.current 在我打印到控制台时确实有一个值。我只有在执行weather.current.temp_c 时才会收到错误消息
【解决方案2】:

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

在第一次渲染时,weather 将被设置为 [],因为这是 useState 设置的。您排队等待稍后完成的效果,然后渲染前置效果元素:

return (
    <div>
      <h1>hello!</h1>
      {console.log(weather.current.temp_c)}
    </div>
  );

因为weather 等于[],所以weather.current 等于undefinedundefined.temp_cTypeError

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

【讨论】:

  • 如果是这样的话。为什么我在执行{console.log(weather.current)} 时能够打印到控制台并且没有出现错误?
  • 因为 [].current 的计算结果为 undefined 而不是抛出 TypeError。访问对象值的任何未定义属性都会返回undefined。相反,尝试访问nullundefined 值的任何属性都会抛出TypeError
  • 明白了,谢谢。解决这个问题的最佳方法是什么?我应该设置一个虚拟的初始状态吗?
  • 这取决于你的目标是什么。我猜你的最终目标不是控制台记录一些东西。相反,您需要为用户呈现一些内容,让他们知道数据正在加载,因此您可以检查是否未填充 weather 并返回类似微调器的内容。然后当效果完成时,您的组件将使用填充的weather 状态重新渲染。
猜你喜欢
  • 2019-06-07
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
相关资源
最近更新 更多