[英]TypeError: Cannot read property 'comments' of undefined in React
I have created a Main Component from which I am making use of the rest of the components.我创建了一个主要组件,我从中使用组件的 rest。 For a component, I am passing in appropriate props through onClick.
对于一个组件,我通过 onClick 传递适当的道具。 Even though the property is correctly defined and passed on, I seem to get this error.
即使该属性已正确定义并传递,我似乎也会收到此错误。 Here are the snippets: 1.Main Component
以下是片段: 1.主要组件
import Menu from './MenuComponent';
import DishDetail from './DishDetailComponent';
import { DISHES } from '../shared/dishes';
onDishSelect(dishId) {
this.setState({
selectedDish: dishId
});
}
// In render:
<Menu dishes={this.state.dishes} onClick={(dishId) => { this.onDishSelect(dishId) }} />
<DishDetail dish={this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]}
In the menucomponent:在菜单组件中:
<div key={dish.id} className="col-12 col-md-5 mt-2">
<Card key={dish.id}
onClick={() => this.props.onClick(dish.id)}>
<CardImg width="100%" src={dish.image} alt={dish.name} />
</div>
In the dishdetail component:在菜式细节组件中:
render() {
const dish = this.props.dish;
const dishdetail = this.renderDish(dish);
const dishcomments = this.renderComments(dish.comments);
if (dish != null) {
return (
<div className="row">
{dishdetail}
{dishcomments}
</div>
);
}
else {
return (<div></div>);
}
}
}
First I thought, the selecteddish is set to null in state of maincomponent at the beginning and that's why the error is occuring.首先,我认为,在 maincomponent 的 state 中,selecteddish 一开始就设置为 null,这就是发生错误的原因。 But then even if I add the null check as above, the error still persists.
但是即使我如上所述添加 null 检查,错误仍然存在。 Where am I getting wrong?
我哪里错了?
In DishDetail component, the dish
receives a value a bit eventually.在 DishDetail 组件中,
dish
最终接收到一个值。 You are making checks but at incorrect place.您正在检查,但在不正确的地方。
So, in your render, make checks on this.props.dish
in the beginning.因此,在您的渲染中,首先检查
this.props.dish
。
render() {
if (this.props.dish) {
const dish = this.props.dish;
const dishdetail = this.renderDish(dish);
const dishcomments = this.renderComments(dish.comments);
return (
<div className="row">
{dishdetail}
{dishcomments}
</div>
);
}
else {
return (<div></div>);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.