React新手求助:点击菜品卡片无法触发DishDetailComponent展示菜品详情
问题排查与修复方案
我帮你梳理了代码里的几个关键问题,正是这些导致点击菜品后没有响应、详情无法展示:
1. 未将选中的菜品传递给DishDetail组件
在MenuComponent的render方法中,你渲染<DishDetail />时没有把选中的selectedDish作为props传过去。DishDetail组件一直尝试读取this.props.dish,但这个值始终是null,所以只会渲染空div。
修复方法:修改Menu组件中DishDetail的调用代码:
// 原代码 <DishDetail /> // 修改后 <DishDetail dish={this.state.selectedDish} />
2. DishDetail组件的render方法缺少return
在DishdetailComponent的render方法末尾,你写了JSX结构但没有用return返回,导致组件无法渲染任何内容。
修复方法:给render方法的JSX加上return:
// 原代码 render() { const dish = this.props.dish; if(dish == null) { return( <div></div> ) } const dishItem = this.renderDish(dish); const dishComment = this.renderComments(dish.comments); <div className="container"> {dishItem} {dishComment} </div> } // 修改后 render() { const dish = this.props.dish; if(dish == null) { return( <div></div> ) } const dishItem = this.renderDish(dish); const dishComment = this.renderComments(dish.comments); return ( <div className="container"> {dishItem} {dishComment} </div> ) }
3. 评论渲染时未正确插值变量
在renderComments方法中,你直接写了cmnt.comment和cmnt.author等字符串,没有用React的变量插值语法({}),导致评论内容只会显示字面量而不是实际数据。另外日期也可以做格式化处理,提升可读性。
修复方法:修改renderComments里的列表项代码:
// 原代码 <li key={cmnt.id}> <p>cmnt.comment</p> <p>--cmnt.author,cmnt.date</p> </li> // 修改后 <li key={cmnt.id}> <p>{cmnt.comment}</p> <p>-- {cmnt.author}, {new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: '2-digit' }).format(new Date(cmnt.date))}</p> </li>
把这三个地方修复后,点击菜品卡片就能正常展示对应的详情和评论了!
内容的提问来源于stack exchange,提问作者divyanshu_31
相关产品推荐
相关产品推荐

