当所有嵌套的 Axios 调用完成时 ReactJS setState

JSE*_*eny 0 asynchronous async-await reactjs es6-promise axios

我在通过 forEach 循环内的嵌套 axios 调用更新状态时遇到问题:

constructor(props) {
    super(props);
    this.state = {
      isLoaded: false,
      items: []
    };
    //Binding fetch function to component's this
    this.fetchFiles = this.fetchFiles.bind(this);
  }

  componentDidMount() {
    this.fetchFiles();
  }

  fetchFiles() {
    axios.get('/list')
    .then((response) => {
      var items = response.data.entries;
      items.forEach((item, index) => {
        axios.get('/download'+ item.path_lower)
        .then((response) => {
          item.link = response.data;
        })
        .catch(error => {
          console.log(error);
        })
      });
      this.setState(prevState => ({
        isLoaded: true,
        items: items
      }));
      console.log(this.state.items);
    })
    .catch((error) => {
      console.log(error);
    })
  }
Run Code Online (Sandbox Code Playgroud)

这个想法是使用 Dropbox 的 API (JavaScript SDK) 获取所有项目,然后对于每个项目,我还需要调用不同的 API 端点来获取临时下载链接并将其分配为新属性。只有在所有项目都附加了链接之后,我才想设置状态并渲染组件。有人可以帮忙解决这个问题吗,我已经花了好几个小时与承诺作斗争:S

Yur*_*nko 5

您可以用来Promise.all等待多个承诺。另请记住,这setState是异步的,您不会立即看到更改。您需要传递回调。

  fetchFiles() {
    axios.get('/list')
    .then((response) => {
      var items = response.data.entries;

      // wait for all nested calls to finish
      return Promise.all(items.map((item, index) => {
        return axios.get('/download'+ item.path_lower)
          .then((response) => {
            item.link = response.data;
            return item
          });
      }));     
    })
    .then(items => this.setState(prevState => ({
        isLoaded: true,
        items: items
      }), () => console.log(this.state.items)))
    .catch((error) => {
      console.log(error);
    })
  }
Run Code Online (Sandbox Code Playgroud)