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

ReactJS报错Cannot read properties of undefined (reading 'name')

问题产生原因

React组件在接口请求返回前会先完成首次渲染,此时你定义的weatherData状态还是初始值空对象{},空对象上不存在location属性,也就是weatherData.location的值为undefined,直接读取undefined的name属性就会抛出Cannot read properties of undefined (reading 'name')的错误。

你在控制台打印weatherData.location能看到数据,是控制台对引用类型值的懒求值机制导致的:首次执行打印时拿到的确实是undefined,但等异步请求完成、状态更新触发组件重渲染后,你在控制台展开之前打印的对象时,控制台会显示该引用的最新值,才会让你误以为首次渲染时数据已经存在。

解决方法
  • 用可选链操作符做属性访问兜底:访问嵌套属性时加上?.,当链路中遇到null/undefined时会直接返回undefined,不会抛出类型错误,比如把打印语句改成console.log(weatherData.location?.name)即可避免控制台报错。
  • 增加条件渲染逻辑:可以把weatherData的初始值设为null标记未加载状态,等接口返回数据后再渲染依赖天气数据的组件,同时可以补充加载提示,示例修改如下:
// 初始值设为null,代表数据尚未加载完成
const [weatherData, setWeatherData] = useState(null)
const [search, setSearch] = useState('London')
const [error, setError] = useState('')

useEffect(() => {
  axios.get(`${baseURL + search}`)
    .then(resp => {
      setWeatherData(resp.data)
    })
    .catch(err => {
      setError(err.message)
      // 请求失败时重置weatherData,避免脏数据导致渲染报错
      setWeatherData(null)
    })
}, [search])

// 可选链访问属性,不会抛错
console.log(weatherData?.location?.name);

return (
  <div className="App">
    <h1 style={{ textAlign: 'center', marginBottom: '2rem' }}>{error}</h1>
    <Search setSearch={setSearch} />
    <div className="container">
      {/* 数据加载完成前显示加载提示,拿到数据后再渲染Info组件 */}
      {weatherData ? <Info weatherData={weatherData} /> : <p>正在加载天气数据...</p>}
    </div>
  </div>
);
  • 子组件内也要做兜底判断:如果Info组件内部直接读取weatherData的嵌套属性,同样需要加可选链或者先判断数据存在再渲染对应内容,避免父组件传值不完整时子组件报错。

内容的提问来源于stack exchange,提问作者Elvis Murseli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:57:11