【问题标题】:axios problem with sending all requests in react在反应中发送所有请求的axios问题
【发布时间】:2022-01-18 23:57:00
【问题描述】:

我在本地存储中有一组项目,我想一次将它们全部发送到我的 API 问题是当我向他们发送所有 API 时,API 告诉我它收到了所有请求,但是这个循环并没有将它们从本地存储中删除,就像它没有得到响应或其他东西一样

let local_items = localStorage.getItem("items")
local_items = JSON.parse(local_items)
loadingToast("Syncing items")
for (let i = 0; i < local_items.length; i++) {
  axios.post('/items', {
    item: local_items[i],
    shop: '1',
    employee: '1'
  }, config).then((response) => {
    if (response.status === 200) {
      local_items.splice(i, 1)
      //it counts down 2 or 3 times then gets stuck on a number
      alert("Item synced" + local_items.length)
      localStorage.setItem("items", JSON.stringify(local_items))
    } else {
      dismissToast()
      errorToast("Error syncing items")
      localStorage.setItem("items", JSON.stringify(local_items))
      return
    }
  }).catch((error) => {
    dismissToast()
    errorToast("Error syncing items")
    localStorage.setItem("items", JSON.stringify(local_items))
    return
  })
}
}

所有项目都会显示警报,但倒计时卡住了。

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    local_items.splice(i, 1) 不是删除元素的好方法,它只对前半部分元素有效,对其余部分无效。

    改用local_items.shift()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多