收到错误TypeError:无法读取React中未定义的属性“ map”

时间:2020-06-04 10:03:11

标签: node.js reactjs

我正在尝试使用Node.JS显示API's React数据并出现此错误。数据使用MongoDB存储。显示upvotes时不会出错。仅在打印注释时出现错误。

这是我要打印的数据。我主要是想打印评论。我不确定在打印数据时我在这里犯了什么错误。

{
        "_id" : ObjectId("5ed8b795e08db8286109e8b0"),
        "name" : "learn-react",
        "upvotes" : 46,
        "comments" : [
                {
                        "user" : "Tom",
                        "text" : "True"
                },
                {
                        "user" : "Tom",
                        "text" : "True"
                }
        ]
}
{
        "_id" : ObjectId("5ed8b795e08db8286109e8b1"),
        "name" : "learn-node",
        "upvotes" : 35,
        "comments" : [
                {
                        "user" : "Levy",
                        "text" : "Thanks"
                }
        ]
}
{
        "_id" : ObjectId("5ed8b795e08db8286109e8b2"),
        "name" : "learn-cv",
        "upvotes" : 6,
        "comments" : [
                {
                        "user" : "Harry",
                        "text" : "Thanks for the info"
                },
                {
                        "user" : "Levy",
                        "text" : "Thanks"
                }
        ]
}
import React, { useState, useEffect } from "react";
import articles from "./Content";
import { Link } from "react-router-dom";
import ArticleList from "../components/ArticleList";
import CommentsList from "../components/CommentsList";

const Articles = ({ match }) => {
  const name = match.params.name;

  const [articleInfo, setArticleInfo] = useState([]);
  //fetching url name/handle from the articles Route path

  useEffect(() => {
    let headers = new Headers({
      "Content-Type": "application/json",
      Accept: "application/json",
    });
    fetch(`/api/articles/${name}`, headers)
      .then((res) => res.json())
      .then(
        (result) => {
          setArticleInfo(result);
          console.log("ex");
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          console.log(error);
        }
      );
  });

  //Return name if url path matches the name of the article
  const foundArticle = articles.find((article) => article.name === name);
  //display articles except the current one
  const otherArticles = articles.filter((article) => article.name !== name);
  /*const displayComments=articleInfo.comments.map((item, i) =>{
    const {user, text} =item;
    return(
      <div>
        <ul>
          <li key={i}>{user}</li>
          <li>{text}</li>
        </ul>
      </div>
    )
  })*/
  return (
    <div>
      {foundArticle ? (
        <div>
          <p>Total likes: {articleInfo.upvotes}</p>

          <h2>{foundArticle.title}</h2>
          <p>{foundArticle.content}</p>

          <CommentsList comments={articleInfo.comments}/>
          <Link className="btn" to="/articles-all">
            All blog
          </Link>
        </div>
      ) : (
        <h4>Not found</h4>
      )}
      <ArticleList articles={otherArticles} />
    </div>
  );
};
export default Articles;

import React from 'react'

 const CommentsList = (props) => {
    return (
        <div>
            {props.comments.map((item,i)=>{
               return <p>{item.user}</p>
            })}
        </div>
    )
}
export default CommentsList;

1 个答案:

答案 0 :(得分:0)

尝试使用逻辑&&运算符进行条件渲染:

const CommentsList = (props) => {
    return (
        <div>
            //this line tries to access props before they are passed
            //{props.comments.map((item,i)=>{
            //make sure it exists before trying to map it 
            {props.comments && props.comments.map((item,i)=>{
               return <p>{item.user}</p>
            })}
        </div>
    )
}