3 回答

TA贡献1765条经验 获得超5个赞
我得到了同样的错误。
在我的例子中,通过在主要组件中选择索引 0 而不是完整数组,错误地传递了单个数组项。
comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId, 10))[0]}在主组件中。
更正版本:
const DishWithId = ({ match }) => {
return (
<DishDetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId, 10))[0]}
comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId, 10))} />
);
}

TA贡献1796条经验 获得超4个赞
我很抱歉这个答案是矫枉过正。
你传入的任何 like 都comment={comment}将作为对象成为 props 的一部分,因此你需要从中解构评论。
您也不需要在条件渲染期间返回空的 div。什么都不返回是一样的。
还有,value != null不够。如果该值是任何其他类型的假值,您的应用程序仍会崩溃,因此!value更安全。
如果您要有条件地内联渲染,则使用&&or 三元? :而不是标准if.
import React from "react";
import { Card, CardImg, CardImgOverlay, CardText, CardBody, CardTitle } from "reactstrap";
const RenderDish = ({ dish }) => (
dish && (
<div className="col-12 col-md-5 m-1">
<Card>
<CardImg width="100%" object src={dish.image} alt={dish.name}></CardImg>
<CardBody>
<CardTitle>{dish.name}</CardTitle>
<CardText>{dish.description}</CardText>
</CardBody>
</Card>
</div>
)
);
const RenderComments = ({ comments }) => (
comments && (
<div className="col-12 col-md-5 m-1">
<h3>Comments</h3>
<ul className="list-unstyled">{
comments.map(comment => (
<div className="container">
<li key={comment.id}>
<p>{comment.comment}</p>
<p>
-- {comment.author},
{new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "short",
day: "2-digit"
}).format(new Date(Date.parse(comment.id)))}
</p>
</li>
</div>
))
}</ul>
</div>
)
);
const DishDetail = ({ dish }) => (
dish && (
<div className="row">
<RenderDish dish={dish} />
<RenderComments comments={dish.comments} />
</div>
)
);
export default DishDetail;

TA贡献2065条经验 获得超14个赞
您传递道具并映射道具而不是访问它:
<RenderComments comments={props.dish.comments} />
// Not RenderComments(comments)
function RenderComments(props) {
...
props.comments.map(...)
}
添加回答
举报