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
相关产品推荐
相关产品推荐

