仅在解决循环内的多次提取后如何在 React 中设置状态

How to setState in React only after multiple fetches inside a loop are resolved

在 React 应用程序中,我试图在我的应用程序中设置状态,只有在我获得大量 AJAX 获取解析以避免多次无用的重新渲染之后。

到目前为止我有这样的东西:

const URL = https://url/api/
const NUM_OF_ITEMS = 10;
let allData = [];

componentDidMount() {
  for (let i = 1; i <= NUM_OF_ITEMS; i++) {
    this.fetchData(`${URL}${i}/`)  //ex. https://url/api/1/, https://url/api/2/...
  }
}

const fetchData = URI => {
  fetch(URI)
  .then(response => response.json())
  .then(data => {
    allData = [ ...allData, data];
  })
  .catch( error => this.setState({ error });
}

现在我想在所有提取全部解析后只有一个 setState,然后将其全部保存到 localStorage 中:

this.setState({ allData })
localStorage.setItem("allData", JSON.stringify(allData))

有什么想法吗?

您想使用 Promise.all:

componentDidMount() {
  const requests = [];
  for (let i = 1; i <= NUM_OF_ITEMS; i++) {
    requests.push(this.fetchData(`${URL}${i}/`));
  }
  Promise.all(requests).then((arrayWithData) => {
     // here you can use setState with all the stuff
  });
}

const fetchData = URI => {
  fetch(URI)
  .then(response => response.json())
}