完成所有嵌套的Axios调用后的ReactJS setState [英] ReactJS setState when all nested Axios calls are finished

查看:379
本文介绍了完成所有嵌套的Axios调用后的ReactJS setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with updating my state from nested axios call inside forEach loop:

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

这个想法是使用它的API(JavaScript SDK)从Dropbox获取所有项目 然后对于每个项目,我还需要调用不同的API端点以获取临时下载链接并将其分配为新属性.只有在所有项目都将附加其链接之后,我才需要setState并呈现该组件.有人可以帮忙吗,我已经花了很多时间兑现诺言:S

The idea is to get all items from Dropbox using it's API (JavaScript SDK) and then for each item I also need to call different API endpoint to get a temporary download link and assign it as a new property. Only after all items will get their links attached I want to setState and render the component. Could somebody please help with this, I spend already multiple hours fighting with promises :S

推荐答案

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

You could use Promise.all to wait for multiple promises. Also keep in mind that setState is async and you wont see immediate changes. You need to pass a callback.

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

这篇关于完成所有嵌套的Axios调用后的ReactJS setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆