React天气应用报Cannot read property 'condition' of undefined
报错根因
- React 组件的执行流程是:首次渲染页面 → 执行副作用逻辑(也就是
useEffect里的异步API请求)。也就是说第一次组件渲染时,异步网络请求还在等待返回结果,此时weatherDatas还是初始的空对象{},根本不存在current、location这些嵌套属性。 - 代码在渲染阶段直接读取
weatherDatas.current.condition.icon这类嵌套字段,相当于对undefined对象取condition属性,就会触发指定的TypeError。 - 你观察到的“临时移除props传值、热更新后再加回就能正常运行”的现象,本质是热更新触发重渲染的时机,刚好赶上异步请求已经完成,
weatherDatas已经被接口返回的完整数据填充,所有嵌套字段都存在,因此不会触发空属性读取错误。
可行的解决方法
方案1:用可选链做空值兜底
访问嵌套接口字段时用可选链语法?.替代.,当中间层级为undefined/null时,表达式会直接返回undefined,不会触发运行时报错:
<WeatherCard icon = {weatherDatas.current?.condition?.icon} location = {weatherDatas.location?.name} condition = {weatherDatas.current?.condition?.text} temperature = {weatherDatas.current?.temp_c} />
方案2:条件渲染,数据就绪后再展示卡片
增加数据存在性判断,接口未返回数据时渲染加载提示,数据完整后再渲染WeatherCard,从逻辑上避免读取不存在的字段:
<div className='d-flex justify-content-center'> {weatherDatas.current && weatherDatas.location ? ( <WeatherCard icon = {weatherDatas.current.condition.icon} location = {weatherDatas.location.name} condition = {weatherDatas.current.condition.text} temperature = {weatherDatas.current.temp_c} /> ) : <p>正在加载天气数据...</p>} </div>
方案3:对齐接口结构设置初始state
将weatherDatas的初始值从空对象修改为和接口返回结构完全匹配的带默认值的对象,让首次渲染时所有要读取的字段都有合法的默认值,不会出现undefined:
const [weatherDatas, setWeather] = useState({ location: { name: '' }, current: { condition: { icon: '', text: '' }, temp_c: 0 } });
额外提醒:当前代码里调用的天气接口用的是
http协议,如果后续把项目部署到https的线上环境,会被浏览器的混合内容安全策略拦截,需要同步把接口地址替换为https开头的地址。
内容的提问来源于stack exchange,提问作者Pepe
相关产品推荐
相关产品推荐

