React访问weather嵌套属性触发Uncaught TypeError问题排查
React中访问OpenWeatherMap API数据时TypeError问题排查
问题原因
你代码里的核心问题是初始状态设置错误:把weather的初始值设成了数组[],但API返回的是一个对象。
组件第一次渲染时,API请求还没完成,weather是初始的空数组:
console.log(weather):直接打印空数组,自然没问题weather['name']:数组没有name属性,会返回undefined,console.log可以正常输出undefined,不会触发报错weather['weather'][0]['main']:数组同样没有weather属性,所以weather['weather']是undefined,接着尝试访问undefined[0]就会直接抛出Uncaught TypeError,导致应用崩溃
解决方案
方案1:修正初始状态类型
把初始state改成空对象{}或者null,更符合API返回的数据类型:
const [weather, setWeather] = useState({});
方案2:使用可选链操作符安全访问嵌套属性
ES6+的可选链?.可以在属性不存在时自动返回undefined,避免报错,直接修改log语句:
{console.log('This is in weather: ', weather?.['weather']?.[0]?.['main'])}
方案3:添加加载状态,等待数据返回后再访问
如果需要在页面展示数据,更规范的做法是加一个加载状态,确保数据存在后再处理:
import React, { useEffect, useState } from 'react'; import './App.css'; function App() { const [weather, setWeather] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch('https://api.openweathermap.org/data/2.5/weather?appid=someapikeyshere&q=irvine') .then((response) => response.json()) .then((data) => { setWeather(data); setLoading(false); }) .catch((err) => { console.log(err.message); setLoading(false); }); }, []); if (loading) { return <div>Loading...</div>; } return ( <div className="App"> {console.log('This is in weather: ', weather)} {console.log('This is in weather: ', weather['name'])} {console.log('This is in weather: ', weather['weather'][0]['main'])} </div> ); } export default App;
内容的提问来源于stack exchange,提问作者SushiRiceOverEggs
相关产品推荐
相关产品推荐

