首页 > 解决方案 > 错误:无法读取未定义 React.JS 的属性“地图”

问题描述

我正在关注 react js 教程,但我一直遇到这个问题

import React from "react";
import NewsCard from "../NewsCard/NewsCard";
const NewsCards = ({ articles }) => {
  return (
    <div>
      {articles.map((article, i) => {
        <NewsCard />;
      })}
    </div>
  );
};

export default NewsCards;

标签: javascriptreactjs

解决方案


似乎您的文章没有 [] 的默认值。您可以如下更改。并且你应该在使用map函数时给出 key 属性。

const NewsCards = ({ articles }) => {
  const data = articles ? articles : []
  return (
    <div>
      {data.map((article, i) => {
        <NewsCard key={article.id}/>;
      })}
    </div>
  );
};

推荐阅读