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

React应用编译报错:TypeError: Cannot read properties of undefined (reading 'comments')

报错根因
  • 初始加载时MainComponent的selectedDish状态值为null,执行菜品过滤逻辑this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]没有匹配结果,返回值为undefined,导致传递给DishDetail组件的dish属性为undefined
  • DishDetail的render方法仅做了无效判断this.props != 'undefined',未校验dish属性是否存在就直接访问this.props.dish.comments,触发空指针类型错误。
修复步骤
  1. 优先修改DishDetail组件的render方法逻辑,增加dish属性存在性校验:
render() {
    console.log(this.props);
    console.log('Dishdetail component render is invoked');
    // 仅当dish存在时渲染内容
    if (this.props.dish) {
        return (
        <div className="container">
            <div className="row">
              <div  className="col-12 col-md-5 m-1">
                {this.renderDish(this.props.dish)}
              </div>
              <div  className="col-12 col-md-5 m-1">
                {this.renderComments(this.props.dish.comments)}
              </div>
            </div>
        </div>
        );
    }
    // 无选中菜品时返回空容器
    return <div></div>
}
  1. 其他可优化的代码问题:
  • 移除废弃的componentWillReceiveProps生命周期方法,你当前的展示层组件不需要额外维护props的state副本,直接使用this.props即可
  • 修正renderComments方法中的标签错误:把<uli>改为合法的<li>标签,把class="list"改为React规范的className="list"
  • 修正componentDidUpdate生命周期中的日志打印错误,避免和componentDidMount的日志混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:15:03