You need to enable JavaScript to run this app. ReactJS读取API返回嵌套字段时触发Cannot read property 'number' of undefined错误
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS读取API返回嵌套字段时触发Cannot read property 'number' of undefined错误

异步嵌套字段读取报错问题

在基于ReactJS开发前端应用时,通过API异步获取站点详情数据,在渲染组件时读取嵌套字段会触发Cannot read property 'number' of undefined报错,目标是从接口返回的结构中正确读取number、numberOfCarriages两个列车相关字段完成页面渲染。

原始实现代码

class ViewStationComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            id: this.props.match.params.id,
            station: {}
        }
    }

    componentDidMount() {
        StationService.getStationById(this.state.id).then(res => {
            this.setState({ station: res.data });
            console.log(res.data);
        })
    }

    render() {
        return (
            <div>
                <div>{this.state.station.name}</div>
                <h1>{this.state.station.trains.number}</h1>
            </div>
        );
    }
}

报错原因

  • 组件初始化时,station的默认值是没有任何嵌套属性的空对象{}
  • 首次渲染阶段,接口请求还未返回结果,此时代码直接执行this.state.station.trains.number取值:JS会先访问到值为undefined的trains属性,再尝试读取这个undefined上的number属性,就会抛出指定的类型错误
  • 只要在接口数据回填前触发组件重渲染,这个报错就会稳定复现

对应的修复方法

  • 方案1:补全state初始兜底结构
    修改构造函数里的state默认值,把嵌套层级的属性都补上初始空值,保证取值链路每一层都存在,不会出现断链:
    this.state = {
      id: this.props.match.params.id,
      station: {
        name: '',
        trains: {
          number: '',
          numberOfCarriages: ''
        }
      }
    }
    
  • 方案2:渲染逻辑增加可选链判断
    修改render函数里的取值逻辑,用可选链操作符逐层判断属性是否存在,从语法层面避免空值读取报错,同时兼容后续要读取的numberOfCarriages字段:
    render() {
      const { station } = this.state
      return (
        <div>
          <div>{station?.name}</div>
          <h1>{station?.trains?.number}</h1>
          <p>车厢数量:{station?.trains?.numberOfCarriages}</p>
        </div>
      );
    }
    
  • 方案3:加载阶段做占位渲染
    判断接口数据是否完整返回,数据未就绪时展示加载占位内容,等station.trains字段存在后再渲染正式内容,从流程上规避空值读取:
    render() {
      const { station } = this.state
      // 数据未加载完成时展示占位
      if (!station.trains) {
        return <div>站点数据加载中,请稍候...</div>
      }
      return (
        <div>
          <div>{station.name}</div>
          <h1>{station.trains.number}</h1>
          <p>车厢数量:{station.trains.numberOfCarriages}</p>
        </div>
      );
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 09:45:04