You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:05:14