简体   繁体   中英

how to fix "Cannot read property 'comments' of undefined" in react

I am extracting array "comments" from an array of objects and when I trying to pass this array to a function I get this error "Cannot read property 'comments' of undefined"

here is a snippet from my code.

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"
      },
      {

in main class, I succeeded to get from DISHES array the right element

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]
            }


    );
  }
}

here I tried to parse "comments" but I couldn't even to pass it to the function "renderComments" , but when I try to pass "this.props.dish" only it works fine

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>

    );
  }
}

You are getting that error because this.state.selectedDishId is undefined and therefore the filter doesn't find a match.

You can add a check before going in the renderComments function like below :

this.props.dish && this.renderComments(this.props.dish.comments)

Component code

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;

here is a complete stackblitz

Reference :

Array filter in javascript

you need to set default props and reqired types, because you can pass on an empty array

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"
          }
        ]
     }

you did not handeled null value you should write

class DishDetail extends Component {
  constructor(props) {
    super(props);
    this.renderComments = this.renderComments.bind(this);
  }

  renderComments(comments) {
   return (
    .....
    );
  }
  render() {
if(this.props.dish!=null)
{
    return (
          <div className="col-12 col-md-5 m-1">
               /*here is the problem*/
            {this.renderComments(this.props.dish.comments)}
          </div>

    );
  }
else
{
<div></div>
}
}
}

you can simply do this,

<div className="col-12 col-md-5 m-1">
     <h4>Comments</h4>
     {this.renderComments(this.props.dish)}
</div>

and then

renderComments(dish) {
    if (dish != null) {
        const commentsList = dish.comments.map((comment) => {
            return (
                <div key={comment.id}>
                    <list className="list-unstyled" tag="list">
                        <li className="mb-2">{comment.comment}</li>
                        <li className="mb-5">-- {comment.author}, {this.dateConverter(comment.date)}</li>
                    </list>
                </div>
            );
        });
        return commentsList;
    }
    else {
        return (
            <div></div>
        )
    }
}

I ran into the same problem. Tried this and it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM