我正在尝试构建一个新闻应用程序,显示每个国家/地区的前 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>
);
}
这是一个初学者项目,所以请记住这一点,哈哈。
最佳答案
因此,您希望将所有新闻项包含在状态中,然后循环它们并为每个新闻项创建一个新闻元素。请求类似于这样:
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>
);
}
或者,如果您知道存储在状态中的对象键名称与新闻组件所期望的完全匹配,则可以像这样传播 Prop :
{this.state.articles.map(article => (
<News {...article}/>
))}
关于javascript - React 中多个项目的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53437343/