React集成OpenWeatherAPI报错:Cannot read property 'temp' of undefined
解决 "Cannot read property 'temp' of undefined" 错误
我来帮你排查这个问题,出现这个错误的核心原因是你的API请求没有正确获取到有效数据,导致response.main为undefined,当你尝试访问response.main.temp时就会抛出这个TypeError。下面是具体的问题点和修复方案:
1. 模板字符串使用错误
你在fetch请求里用了单引号包裹URL,但模板字符串需要用**反引号()**才能解析${变量}语法。单引号会把${city}和${country}当作普通字符串发送给API,导致请求的URL无效,API返回错误响应,自然不存在main`属性。
修复代码:
// 把单引号改成反引号 const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&units=metric&appid=${api_key}`);
2. setstate拼写错误
你在更新状态时写了this.setstate({...}),React的状态更新方法是大写的S:this.setState({...})。小写的setstate会导致状态无法正常更新,同时可能引发其他异常。
修复这一行:
this.setState({ temperature: response.main.temp, // ...其他状态属性 })
3. 状态赋值逻辑错误
你把pressure的值错误赋值成了response.weather[0].icon,而icon属性却没有被正确赋值,这会导致后续Forecast组件里的pressure显示图标ID,而图标地址为空。正确的赋值应该是:
this.setState({ temperature: response.main.temp, city: response.name, country: response.sys.country, humidity: response.main.humidity, pressure: response.main.pressure, // 改为main下的pressure属性 icon: response.weather[0].icon, // 正确赋值icon description: response.weather[0].description, error:"" })
4. 可选链保护(可选优化)
为了避免API返回异常(比如城市名拼写错误)导致的类似崩溃,可以在访问嵌套属性时使用可选链操作符?.,这样即使某个属性不存在也不会抛出错误:
temperature: response.main?.temp, country: response.sys?.country, icon: response.weather?.[0]?.icon, description: response.weather?.[0]?.description,
5. 补充错误处理逻辑
在fetch之后最好加上状态码检查,判断请求是否成功,避免无效响应导致的异常:
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&units=metric&appid=${api_key}`); if (!api_call.ok) { throw new Error('请求失败,请检查城市和国家名称是否正确'); } const response = await api_call.json();
把这些问题都修复后,你的天气获取功能应该就能正常工作了。另外测试时建议使用API识别的国家代码(比如UK用"GB"),能提升请求成功率。
内容的提问来源于stack exchange,提问作者Tarun007
相关产品推荐
相关产品推荐

