javascript - 许多项目的 setState 反应
问题描述
我正在尝试构建一个显示每个国家/地区前 20 篇文章的新闻应用程序。但是,我尝试将我的 setState 调用放在一个循环中,但我很快意识到它们被覆盖了,唯一会显示的是最后一个。我想知道如何在不覆盖以前的条目的情况下实现这一目标。先感谢您!
//the following code is inside my App.js file and inside the App component
getNews = async (e) => {
e.preventDefault();
const country = e.target.elements.country.value;
const api_call = await fetch(this.buildURL(country));
const data = await api_call.json();
if (country) {
console.log(data);
//i changed this to just display the first article out of 20
this.setState({
title: data.articles[0].title,
image: data.articles[0].urlToImage,
description: data.articles[0].description,
author: data.articles[0].author,
link: data.articles[0].url,
err: ""
});
}
else {
this.setState({
title: undefined,
image: undefined,
description: undefined,
author: undefined,
link: undefined,
err: "Please enter valid country"
});
}
}
render() {
return(
<div>
<Titles />
<Form getNews={this.getNews}/>
<News title={this.state.title}
image={this.state.image}
description={this.state.description}
author={this.state.author}
link={this.state.link}
err={this.state.err}
/>
</div>
);
}
这是一个初学者项目,所以请记住这一点哈哈。
解决方案
因此,您希望在 state 中包含所有新闻项目,然后循环它们并为每个新闻创建一个 News 元素。请求是这样的:
getNews = async e => {
e.preventDefault();
const country = e.target.elements.country.value;
if (!country) {
this.setState({
articles: null,
err: "Please enter valid country"
});
}
let data;
try {
data = await fetch(this.buildURL(country)).then(res => res.json());
} catch (error) {
this.setState({
articles: null,
err: "Please enter valid country"
});
}
if (data) {
this.setState({
articles: data.map(article => ({
title: article.title,
image: article.urlToImage,
description: article.description,
author: article.author,
link: article.url
}))
});
}
};
虽然我不保证它没有错误!
然后,当您拥有所有文章状态时,您可以遍历它们:
render() {
return (
<div>
<Titles />
<Form getNews={this.getNews} />
{this.state.articles.map(article => (
<News
title={article.title}
image={article.image}
description={this.state.description}
author={article.author}
link={article.link}
err={article.err}
/>
))}
</div>
);
}
或者,如果您知道存储在 state 中的对象键名与 News 组件所期望的完全匹配,则可以像这样传播道具:
{this.state.articles.map(article => (
<News {...article}/>
))}
推荐阅读
- java - 使用 AlarmManager 设置一些通知并取消其中一个
- javascript - 可以从html5或者flash player中获取值吗?(百家乐机器人)
- kubernetes - 调整 Kubernetes Job 行为,保留 kubernetes pod 日志
- r - 如何使用 RStudio 从 excel 文件中读取列和子列并将其显示到数据框中
- node.js - NodeJs Async/Await 未正确执行
- python - 将数字写入excel时应用公式
- android-studio - 运行应用程序时返回错误“不支持”
- php - SwiftMailer 强制 SMTPAuth 像 PHPMailer
- google-apps-script - 当我调用电子表格名称时,自动电子邮件发票错误
- postgresql - 如何统计数据库中表的所有行和列?