我是React js的新手,我正在尝试使用它创建一个项目.在使用地图功能时,我遇到了错误



我正在创建一个网站来传递新闻。我是reactJS的初学者,我面临错误:"TypeError: Cannot read properties of undefined (reading 'map')">

我试着在网上搜索这个,但无法理解这段代码有什么问题。有人能帮帮我吗?

下面是代码片段:
import React, { Component } from "react";
import NewsItem from "./NewsItem";
export class News extends Component {
constructor() {
super();
console.log("HELLO there");
this.state = {
articles: this.articles,
loading: false,
};
}
render() {
return (
<div>
This is a news component
//This is the part which shows error
{this.state.articles.map((element) => {
console.log(element)
})}
<div className="row">
<div className="col-md-3">
<NewsItem imageUrl="https://photos5.appleinsider.com/gallery/44585-86572-210921-macOSBigSur-xl.jpg" />
</div>
</div>
</div>
);
}
}
export default News;

您的this.articles不作为属性存在于您的类中。您只需添加

this.articles = [ { id: 1, title: "Article 1" }, { id: 2, title: "Article 2" } ];

在你的console.log()语句之后。

最新更新