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

ReactJS天气应用运行报错:Cannot read properties of undefined (reading 'main')

报错原因

React组件首次渲染时,你用于存储天气数据的weather状态还未被接口返回值赋值,默认初始值大概率为空对象,此时直接访问weather.main会读取到undefined,触发该类型错误。你现有的typeof判断写法不够简洁,也存在遗漏覆盖的嵌套字段场景。

修复方案
  • 方案1:给weather状态设置带兜底字段的初始值,避免空对象读取嵌套属性报错
// 定义状态时直接加上所有用到的嵌套字段兜底
const [weather, setWeather] = useState({
  main: {},
  sys: {},
  weather: [{}],
  name: ''
})
  • 方案2:所有嵌套属性访问替换为可选链操作符?.,比typeof判断更简洁可靠,不需要额外写类型判断逻辑
return (
 <div className={weather?.main?.temp > 16 ? 'app warm' : 'app'}>
   <main>
   <div className="search-box">
     <input type='text' 
      className='search-bar' 
      placeholder='Search ...'
      onChange={e => setQuery(e.target.value)}
      value={query}
      onKeyPress={search}
      />
    </div>
    
    {weather?.main ? (
     <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='temp'>
      {Math.round(weather?.main?.temp)}
      </div>
      <div className='weather'>
      {weather?.weather?.[0]?.main}
      </div>
      </div>
     </div>
    ): (' ')}
  </main>
   </div>
  );
  • 方案3:新增加载状态,接口请求完成前只渲染加载提示,不渲染依赖天气数据的内容,从根源避免空数据访问问题

内容的提问来源于stack exchange,提问作者Knowexx Ke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:04