我正在嘗試使用天氣 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 數據嗎?
如何遍歷json api數據對象
白板的微信
2023-05-25 16:29:40