亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何遍歷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將是未定義的,因此會出現錯誤。

要么使用一組更完整的默認數據?;驕y試是否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 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號