【发布时间】:2022-01-17 01:34:46
【问题描述】:
我正在为我的项目创建一个新闻应用程序,我所做的基本上是从 API 获取新闻文章数组,然后将其存储在我本地内存中的文章数组中,然后我使用 map 方法数组,从而在我的网页上呈现文章,但现在我收到此错误:
我看了一些类似的问题,我认为构造函数的范围有什么问题。 编辑:我在 setstate 部分错了,但我只是在尝试,但原始代码是这样的:
this.state = {
articles: this.articles
}
上面的代码是在下面的代码是完整代码之前的setstate位置的原始代码
articles = [];
constructor() {
super();
console.log(typeof articles);
this.state = {
articles: this.articles
}
// let category = 'top-headlines';
// let country = 'in';
}
async componentDidMount() {
const YOUR_API_KEY = 'cant show you this';
// let q = '';
let url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=${YOUR_API_KEY}`;
const FetchNews = async () => {
const response = await fetch(url);
const parsedjson = await response.json();
console.log(parsedjson);
this.setState({ articles: parsedjson.articles });
}
FetchNews();
}
render() {
return (
<div className="container p-1" style={{ backgroundColor: '#F0CE57' }}>
<div className="noogle">
<h1>Noogle</h1>
<input type="text" placeholder='Search News' />
</div>
<div className="row">
{this.state.articles.map((element) => {
return <div className="col-md-4" key={element.url}>
<NewsCard title={element.title} desc={element.description} imgurl={element.urlToImage} url={element.url} />
</div>
})}
</div>
</div>
)
}
}
【问题讨论】:
-
您没有正确初始化状态。在构造函数中你只是将属性设置为一个对象,不要在这里调用
setState。 -
@BrianThompson 实际上我只是在尝试,但实际代码是这样的:`this.state = {articles:this.articles}`
标签: reactjs api react-class-based-component