首页 > 解决方案 > 许多项目的 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>
    );
    }

这是一个初学者项目,所以请记住这一点哈哈。

标签: javascriptarraysjsonsetstate

解决方案


因此,您希望在 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}/>
  ))}

推荐阅读