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,触发空指针类型错误。
修复步骤
- 优先修改
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> }
- 其他可优化的代码问题:
- 移除废弃的
componentWillReceiveProps生命周期方法,你当前的展示层组件不需要额外维护props的state副本,直接使用this.props即可 - 修正
renderComments方法中的标签错误:把<uli>改为合法的<li>标签,把class="list"改为React规范的className="list" - 修正
componentDidUpdate生命周期中的日志打印错误,避免和componentDidMount的日志混淆。
内容的提问来源于stack exchange,提问作者chsm19
相关产品推荐
相关产品推荐

