首页 > 解决方案 > 在 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>
            )
         })

    }

标签: reactjs

解决方案


看起来有几件事要解决。

第一的。该DishDetail组件需要一个render()可以读取作为输入传递的属性的方法。

第二。在 is或它MenuComponent包含. 因此,您可以尝试访问,但不能或。statenull{selectedDish: dish}this.state.selectedDishthis.state.dishthis.state.comment

您可能希望console.log(state)在函数内部使用类似的东西,render()这样您就可以在控制台中查看您的状态以及您将哪些值作为道具传递给其他组件。

希望能帮助到你。再见。


推荐阅读