reactjs - 在 React 中未定义,它不识别道具 - 但为什么呢?
问题描述
我需要在DishDetailComponent.js
文件中获取 DishDetail 组件,以呈现从特定项目传递给它的道具,该项目已在MenuComponent.js
. 目前,我的renderComments()
语法使负载崩溃。如果我把它拿出来,它会加载页面,当我点击其中一个显示的菜肴时不会崩溃,但它什么也没做。使用 React 工具时,它告诉我 DishDetail 组件有 2 个道具 - 菜和评论,但它说它们是未定义的。
我的问题是双重的(我认为)-a)我没有正确的代码让DishDetail
组件接收所选项目的道具。
b)我如何编写正确的语法来访问菜品的评论属性,以显示对特定菜品的评论。
MenuComponent.js
class Menu extends Component {
constructor(props) {
super(props);
this.state = {
selectedDish: null
};
}
onDishSelect(dish){
this.setState({selectedDish: dish});
}
render() {
const menu = this.props.dishes.map((dish) => {
return (
<div key={dish.id} className="col-12 col-md-5 m-1">
<Card onClick={() => this.onDishSelect(dish)}>
<CardImg width="100%" object src={dish.image} alt={dish.name} />
<CardImgOverlay>
<CardTitle>{dish.name}</CardTitle>
</CardImgOverlay>
</Card>
</div>
);
});
return (
<div className="container">
<div className="row">
{menu}
</div>
<DishDetail dish={this.state.dish} comments={this.state.comments}/>
</div>
);
}
}
export default Menu;
DishDetailComponent.js
class DishDetail extends Component {
constructor (props){
super(props);
}
renderDish(dish) {
if (dish != null){
return (
<div className="col-12 col-md-5 m-1">
<Card>
<CardImg top src={this.props.dish.image} alt={this.props.dish.name} />
<CardBody>
<CardTitle>{this.props.dish.name}</CardTitle>
<CardText>{this.props.dish.description}</CardText>
</CardBody>
</Card>
</div>
)
} else {
return (
<div>
</div>
)
}
}
renderComments(dish) {
const comment = this.props.comments.map((comments) => {
return (
<div className="col-12 col-md-5 m-1">
<p>{this.props.comment.comment}</p>
<p>{this.props.comment.author}</p>
<p>{this.props.comment.date}</p>
</div>
)
})
}
解决方案
看起来有几件事要解决。
第一的。该DishDetail
组件需要一个render()
可以读取作为输入传递的属性的方法。
第二。在 is或它MenuComponent
包含. 因此,您可以尝试访问,但不能或。state
null
{selectedDish: dish}
this.state.selectedDish
this.state.dish
this.state.comment
您可能希望console.log(state)
在函数内部使用类似的东西,render()
这样您就可以在控制台中查看您的状态以及您将哪些值作为道具传递给其他组件。
希望能帮助到你。再见。
推荐阅读
- javascript - 使用环境变量在“angular.json”中构建期间动态替换文件
- c# - 检测循环 Unity3D 中最后一个对象的位置
- java - 用于组合多个序列的正则表达式
- charts - Power bi fit width of chart without scroll
- python - ManyToMany relationship between Category and Product in Ecommerce
- android - Android ViewPager2 setPageMargin unresolved
- php - 如何上传文件并将文件信息和用户详细信息添加到 mySQL
- amazon-web-services - 不断将数据从 aws aurora mysql 移动到 aws s3
- node.js - How to write logic inside Nest js Middleware and Guard
- angular - 唯一的浏览器 ID