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

React调用天气API渲染数据时报Cannot read property 'country' of undefined错误

问题原因分析
  • 初始值判断逻辑错误:你给weather设置的初始值是空对象{},typeof {}返回的是object而非undefined,所以你写的typeof weather != 'undefined'判断永远成立,首次渲染时weather为空对象,weather.sys为undefined,读取weather.sys.country就会触发报错。
  • 按键判断拼写错误:你写的触发条件是evt.key === "Entre",但标准的回车键键值是Enter,拼写错误导致你按回车不会触发请求,weather始终是空对象,报错一直存在。
  • 请求URL格式错误:fetch地址中APPID${api.key}缺少等号,正确格式应为APPID=${api.key},错误的请求参数会导致接口返回异常数据,即使触发请求也拿不到包含sys字段的正确结果。
修复方案
  1. 调整渲染逻辑,使用可选链避免属性读取报错,或者修改初始值和判断条件:
// 方式1:使用可选链操作符,兼容属性不存在的场景
{weather?.name ? (
  <div>
    <div className="location-box">
      <div className="location">
        {weather.name},{weather?.sys?.country} 
      </div>
      <div className="date"> {dateBuilder(new Date())} </div>
    </div>
    <div className="weather-box">
      <div className="weather-temperature">15*C</div>
      <div className="weather">Sunny </div>
    </div>
  </div>
) : ("NULL")}

// 方式2:修改weather初始值为null
// const [weather, setWeather] = useState(null);
// 判断直接写weather ? (...) : ("NULL")
  1. 修正按键判断拼写:
if (evt.key === "Enter") {
  // 请求逻辑
}
  1. 修正请求URL的参数格式:
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
  1. 建议添加请求错误捕获逻辑,避免接口异常导致的问题:
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
  .then((res) => res.json())
  .then((result) => {
    setWeather(result);
    setQuery("");
    console.log(result);
  })
  .catch(err => {
    console.error("请求失败:", err)
    // 可以在这里加自定义错误提示逻辑
  })

内容的提问来源于stack exchange,提问作者Ihtisham Khattak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:45:04