【问题标题】:How do you await multiple axios calls with pagination in React?你如何在 React 中等待多个带有分页的 axios 调用?
【发布时间】:2020-11-17 02:59:47
【问题描述】:

React Pagination 和多个 Axios 调用

我正在尝试映射一组数字并按顺序对每个数字进行 api 调用。 但是,我调用的 api 有分页结果,所以我必须多次运行 'function 2' 并附加 'next' 光标。

我的问题是,在移动到循环中的下一个数组项之前,我无法让整个功能等到没有更多的分页结果。

以下是我目前的代码:-

function1() {
    let arr = ['837493000', '837493001'];
    Promise.all(arr.map((num) => this.function2(num))).then(() => {
        this.function3();
    });
}
  
function2(number, after) {

    let api = `https://test-api.local/${number}?client_id=123456789`;

    if(after){
      api = `https://test-api.local/${number}?client_id=123456789&cursor=${after}`;
    }

    const result = axios.get(api, {
      method: 'get',
      headers: {
        'Client-ID': '123456789'
      }
    })
    .then((response) => response.data)
    .then((responseText) => {

      if(responseText){
         let data = responseText.comments;

         if(responseText._after){
           this.function2(number, responseText._after);
         }

         return data;

      }
    });
 }
  
function3() {
  console.log('I ran');
}

componentDidMount(){
   this.function1();
}

它正在运行序列中的前 2 个数字,然后调用函数 3.. 被难住了几个小时.. 任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: javascript reactjs ecmascript-6 pagination axios


    【解决方案1】:

    如果您通过调用function2(一个promise)返回结果,则返回的function2 返回的promise 将被链接到它:

         if(responseText._after){
           return this.function2(number, after)
             .then(others => [data, ...others]);
         }
    
         return [data];
    

    【讨论】:

    • 我收到错误“其他人不可迭代”。对 api 的调用没有按顺序发生,函数 3 在前 2 个初始调用之后仍在运行。
    猜你喜欢
    • 2019-12-29
    • 2019-07-08
    • 2019-06-05
    • 2018-05-29
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多