【问题标题】:Handling axios cancel in loop在循环中处理 axios 取消
【发布时间】:2018-09-27 03:03:28
【问题描述】:

我有以下场景

const config = {
    timeout: 30000,
    headers: {
        Authorization: ``
    },
    cancelToken: cancelSource.token
};

for (var i = 0; i < data.length; i++) {
    let itr = 0;
    axios
        .post("/my/url", "", config)
        .then(response => {
            if (response.status === 200) {
                if (i === itr) {
                    //set state here
                }
            }
        })
        .catch(error => {
            if (axios.isCancel) {
                // How to know if the cancel stops already?
            }
        });
}

例如: 我有 16 件商品,8 件商品被取消。我怎么知道取消是否完成? 所以我可以在这里设置一些后期处理。

【问题讨论】:

  • catch语句收到错误时不就取消了吗?

标签: javascript reactjs axios


【解决方案1】:

axios.isCancel 是一个期望错误作为参数的函数。但你称它为钥匙。所以

改变

  .catch(error =>{
      if(axios.isCancel){
          // How to know if the cancel stops already?
     }
  });

  .catch(error =>{
      if(axios.isCancel(error)){
          // How to know if the cancel stops already?
      }
   });

通过上述更改,您可以确定请求何时被取消。您可以简单地使用局部变量来管理接收到的数据,直到它被取消。之所以需要在这里使用局部变量,是因为循环内部不允许使用 setState。所以将所有数据推入数组,最后将该数组分配给循环外的组件状态

【讨论】:

  • 所以在我的取消中我会做一些类似 cancelSource.cancel(someState) 的事情?
  • 你需要传递你在 catch 块中得到的错误。我更新了答案中的代码,您可以查看
  • .catch(error => { if(axios.isCancel(error)){ console.log(error); } 我试过了,但错误未定义
  • 查看此线程接受的答案以获取更多详细信息stackoverflow.com/questions/44852054/…
猜你喜欢
  • 2020-02-09
  • 1970-01-01
  • 2019-08-06
  • 2010-12-09
  • 2019-03-14
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多