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

React中OpenWeather API天气图标显示破碎,请求排查代码问题

解决OpenWeatherMap天气图标显示破碎的问题

我帮你排查了代码里的两个关键问题,正是它们导致图标显示异常:

1. App.js中State赋值错误,图标未被正确更新

你在getWeather方法的setState里,给icon赋值的写法完全不对——直接写data.weather[0].icon是无效的,必须明确写成键值对形式icon: data.weather[0].icon。另外为了避免API返回数据异常(比如weather数组为空)导致报错,建议加上可选链操作符(?.)做安全访问。

修正后的setState代码片段:

this.setState({
  temperature: data.main.temp,
  city: data.name,
  main: data.main,
  icon: data.weather[0]?.icon, // 修正赋值语法,添加可选链防报错
  rain: data.rain,
  pressure: data.main.pressure,
  humidity: data.main.humidity,
  description: data.weather[0]?.description,
  error: ""
});

2. Weather.js中图片URL的模板字符串使用错误

你写的图片URL用了单引号('),但模板字符串必须用**反引号(`)**才能解析变量${props.icon}。原来的写法会把${props.icon}当成字符串的一部分,导致请求的URL是无效的http://openweathermap.org/img/w/${props.icon}.png,自然显示破碎图片。

修正后的img标签代码:

<img className="img-fluid" src={`http://openweathermap.org/img/w/${props.icon}.png`} alt="Weather icon" />

额外小建议

  • 给img标签加上alt属性,提升页面可访问性
  • 可以在Weather组件里判断props.icon是否存在,避免加载无效图片:
    {props.icon && <img className="img-fluid" src={`http://openweathermap.org/img/w/${props.icon}.png`} alt="Weather icon" />}
    

内容的提问来源于stack exchange,提问作者Leo Bogod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:54:15