簡體   English   中英

如何在反應中修復“無法讀取未定義的屬性'評論'”

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

我正在從對象數組中提取數組“評論”,當我嘗試將此數組傳遞給函數時,出現此錯誤“無法讀取未定義的屬性‘評論’”

這是我的代碼片段。

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

在主類中,我成功地從 DISHES 數組中獲取了正確的元素

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


    );
  }
}

在這里,我試圖解析“評論”,但我什至無法將其傳遞給函數“renderComments”,但是當我嘗試傳遞“this.props.dish”時,它只能正常工作

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>

    );
  }
}

您收到該錯誤是因為this.state.selectedDishId undefined ,因此filter找不到匹配項。

您可以在進入 renderComments 函數之前添加一個檢查,如下所示:

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

組件代碼

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;

這是一個完整的堆棧閃電戰

參考 :

javascript中的數組過濾器

您需要設置默認道具和所需類型,因為您可以傳遞一個空數組

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

你沒有處理你應該寫的空值

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

你可以簡單地做到這一點,

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

進而

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

我遇到了同樣的問題。 試過這個,它奏效了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM