【问题标题】:Getting an error TypeError: Cannot read property 'map' of undefined in React收到错误 TypeError: Cannot read property 'map' of undefined in React
【发布时间】:2020-06-04 10:03:11
【问题描述】:

我正在尝试使用 React 显示 Node.JS API's 数据并收到此错误。数据使用MongoDB 存储。显示赞成票时不会出错。它只会在打印出 cmets 时出错。

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

{
        "_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;

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,一切正常。但是,我不确定它为什么解决了这个问题。我知道这会检查 cmets 是否为真,然后只有它会映射它。但它是如何解决的呢?
    • 我绝不是专家,所以对它持保留态度。据我了解,反应,通过道具传递指向值的指针,而不是实际值。因此,在初始渲染时,这些指针被映射,但由于您从外部源 (API) 获取数据,这些指针引用尚未定义的值。收到数据后,声明值并且组件可以读取它。希望能澄清一点
    猜你喜欢
    • 2020-12-26
    • 2023-02-22
    • 1970-01-01
    • 2023-01-19
    • 2020-09-20
    • 2019-02-12
    • 2020-05-02
    • 2021-04-10
    • 2021-09-20
    相关资源
    最近更新 更多