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(...)
}
添加回答
舉報