我从一个对象数组中提取数组“注释”,当我尝试将此数组传递给函数时,我收到此错误“无法读取属性'注释'未定义”
这是我代码中的一个片段。
export const DISHES = [
{
id: 0,
name: "Uthappizza",
image: "assets/images/uthappizza.png",
category: "mains",
label: "Hot",
price: "4.99",
comments: [
{
id: 0,
rating: 5,
comment: "Imagine all the eatables, living in conFusion!",
author: "John Lemon",
date: "2012-10-16T17:57:28.556094Z"
},
{
在主类中,我成功地从DISHES数组中获取了正确的元素
import { DISHES } from "../shared/dishes";
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null
};
}
onDishSelect(dishId) {
this.setState({
selectedDishId: dishId
});
}
render() {
return (
<DishDetail
dish={
this.state.dishes.filter(
dish => dish.id === this.state.selectedDishId
)[0]
}
);
}
}
在这里我试图解析“评论”,但我甚至无法将其传递给函数“renderComments”,但是当我尝试传递“this.props.dish”时它只能正常工作
class DishDetail extends Component {
constructor(props) {
super(props);
this.renderComments = this.renderComments.bind(this);
}
renderComments(comments) {
return (
.....
);
}
render() {
return (
<div className="col-12 col-md-5 m-1">
/*here is the problem*/
{this.renderComments(this.props.dish.comments)}
</div>
);
}
}
你得到那个错误,因为this.state.selectedDishId
是undefined
,因此filter
找不到匹配。
您可以在进入renderComments函数之前添加一个检查,如下所示:
this.props.dish && this.renderComments(this.props.dish.comments)
组件代码
import React, { Component } from 'react';
class DishDetail extends Component {
constructor(props) {
super(props);
this.renderComments = this.renderComments.bind(this);
}
renderComments(comments) {
return comments.map((comment)=> {
return(
<p>
{comment.comment}
</p>
)
})
}
render() {
return (
<div className="col-12 col-md-5 m-1">
{this.props.dish && this.renderComments(this.props.dish.comments)}
</div>
);
}
}
export default DishDetail;
这是一个完整的stackblitz
参考:
你需要设置默认道具和必需的类型,因为你可以传递一个空数组
import PropTypes from 'prop-types';
DishDetail.propTypes = {
dish: PropTypes.object
};
DishDetail.defaultProps = {
dish: {
id: 0,
name: "Uthappizza",
image: "assets/images/uthappizza.png",
category: "mains",
label: "Hot",
price: "4.99",
comments: [
{
id: 0,
rating: 5,
comment: "Imagine all the eatables, living in conFusion!",
author: "John Lemon",
date: "2012-10-16T17:57:28.556094Z"
}
]
}