在React应用程序中,只有在我解决了很多AJAX提取以避免多次无用的重新渲染之后,才尝试在我的应用程序中设置setState。

到目前为止,我有这样的事情:

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())
}

10-02 15:33