简体   繁体   English

如何在反应中修复“无法读取未定义的属性'评论'”

[英]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在主类中,我成功地从 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]
            }


    );
  }
}

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在这里,我试图解析“评论”,但我什至无法将其传递给函数“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>

    );
  }
}

You are getting that error because this.state.selectedDishId is undefined and therefore the filter doesn't find a match.您收到该错误是因为this.state.selectedDishId undefined ,因此filter找不到匹配项。

You can add a check before going in the renderComments function like below :您可以在进入 renderComments 函数之前添加一个检查,如下所示:

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 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.试过这个,它奏效了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError:无法读取 React 中未定义的属性“注释” - TypeError: Cannot read property 'comments' of undefined in React 如何修复无法读取未定义 react-redux 的属性“名称” - how to fix Cannot read property 'name' of undefined react-redux 如何修复无法读取React中未定义的&#39;exportPDFWithComponent&#39;属性? - How to fix Cannot read property 'exportPDFWithComponent' of undefined in React? 如何修复“无法读取未定义的属性&#39;sendMessage&#39;”反应聊天系统 - How to fix “ Cannot read property 'sendMessage' of undefined” react chat system 如何修复:React DOM 库的“无法读取未定义的属性‘forEach’” - How to fix: 'Cannot read property 'forEach' of undefined' of react DOM library 如何解决discord.js中的“无法读取未定义的属性&#39;反应&#39;” - How to fix “Cannot read property 'react' of undefined” in discord.js 如何修复 React 项目中的“TypeError:无法读取未定义的属性‘继承’”? - How to fix “TypeError: Cannot read property 'inherits' of undefined” in React project? 如何使用 react 和 typescript 修复错误无法读取未定义的属性? - How to fix error cannot read property of undefined using react and typescript? 如何修复“无法读取未定义的属性”? - how to fix 'Cannot read property of undefined'? 如何修复无法读取未定义的属性“hasOwnProperty”? - How to fix Cannot read property 'hasOwnProperty' of undefined?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM