React天气应用开发报Cannot read property '0' of undefined如何解决
报错原因
你遇到的报错是组件渲染时序和属性安全访问的问题:
WeatherDetail首次渲染时,useEffect内的接口请求还未返回,weatherInfo是初始空对象,weatherInfo.weather为undefined,直接访问[0]触发类型错误。- 你将
imgCode = weatherInfo.weather[0].icon放在组件顶层执行,不管城市是否选择、数据是否返回,每次渲染都会执行这行取值逻辑,哪怕后续渲染时判断了city !== "",顶层的取值逻辑依然会先执行,所以报错不会消失。
修复方案
直接修改WeatherDetail.js代码即可:
const [weatherInfo, setWeatherInfo] = useState({}); useEffect(() => { // 城市为空时不发送无效请求 if (!city) return axios.get(setApiAddress(city)) .then((response) => { setWeatherInfo(response.data); }) .catch(err => { // 可自行添加错误提示逻辑 console.error('天气数据获取失败', err) }) }, [city, setApiAddress]); return ( <div> {/* 新增weather属性存在性判断,用可选链做安全校验 */} {city !== "" && weatherInfo?.weather?.length > 0 && ( <div className="card"> <img className="card-img-top" alt="天气图标" src={`https://openweathermap.org/img/wn/${weatherInfo.weather[0].icon}.png`} /> <div className="card-body"> <h5 className="card-title">{weatherInfo.name}</h5> <p className="card-text"> 示例文本 </p> </div> </div> )} </div> );
补充优化说明
- 用可选链
?.做属性安全访问,只有前序属性存在时才会继续读取后续属性,避免空值报错 - 把图标的取值逻辑移到渲染判断内部,仅当城市已选择、天气数据已返回时才执行取值逻辑,避免无效执行
- 给接口请求增加catch异常捕获,避免接口请求失败时页面报错,也方便后续加用户友好的错误提示
内容的提问来源于stack exchange,提问作者Mehmet Aziz Algüllü
相关产品推荐
相关产品推荐

