如何从OpenWeatherMap API返回的JS对象中获取weather[0].icon?
解决方案
你需要修改图片src的取值逻辑,因为weather是一个数组,icon字段在数组的第0个元素里,所以要先访问数组索引[0]再获取icon:
修改后的图片标签代码:
<img src={`http://openweathermap.org/img/wn/${currentWeather?.weather?.[0]?.icon}@2x.png`} alt="天气图标"></img>
补充说明:
- OpenWeatherMap返回的
weather字段是包含天气信息对象的数组,即便只有一条天气数据,也会以数组形式返回,因此必须通过[0]获取第一个元素。 - 保留
?.可选链操作符,可避免数据未加载完成时出现Cannot read properties of undefined的报错。
你也可以在useEffect的回调里打印response.data.weather,确认数组结构:
console.log(response.data.weather);
内容的提问来源于stack exchange,提问作者hanasiyou
相关产品推荐
相关产品推荐

