当前位置: 代码迷 >> JavaScript >> 关于提交redux表单循环axios发布多值
  详细解决方案

关于提交redux表单循环axios发布多值

热度:94   发布时间:2023-06-13 11:40:34.0

在以下代码中显示提交功能,在以下代码中显示我要在redux表单上提交的复选框的表单列表,以将每个值发布到axios api,

values = {example1:true,example2:true,example3:false,example4:true}我的代码中的预期输出将打印每个键,然后发布它,但现在这样做会循环和控制台(example1,.... ,example4)之后,将为同一键调用该帖子4次

submit(values) {
let data={
    "status":"INVITED",
    "buyerId": localStorage.getItem("companyId"),
    "joinType": "B",
    "supplierId": ""          
}
for (var key in values) {
    if (values[key]) {

        data.supplierId=key
       console.log(key)
       postWithAuth("networkmgtservice/api/networks",data).then((response) => {
        let status=response.data.statusCode;
        if(status="000"){
              console.log(key)
            $(`#${keyVar}`).html("Successfully sent")
        }
        else if(status=="999"){

            $(`#${keyVar}`).html(response.data.errorDescription)
        }
      })
        .catch((error) => {
            console.log(error)
        })
    }

不要使用var申报时,内环你正在做异步任务按声明的变量的循环变量var不维护自己的状态和循环总是快于你的API调用被更新到最后一个值在循环,所以你循环变量将仅保留地图中最后一项的值。 而是使用let声明循环变量,因为它们保持状态。

submit(values) {
let data={
    "status":"INVITED",
    "buyerId": localStorage.getItem("companyId"),
    "joinType": "B",
    "supplierId": ""          
}
for (let key in values) {
    if (values[key]) {
       let requestData = {...data};
       requestData.supplierId=key
       console.log(key)
       postWithAuth("networkmgtservice/api/networks",requestData)
           .then((response) => {
                let status=response.data.statusCode;
                if(status="000"){
                    console.log(key)
                    $(`#${keyVar}`).html("Successfully sent")
                }
                else if(status=="999"){
                    $(`#${keyVar}`).html(response.data.errorDescription)
                }
           })
            .catch((error) => {
                 console.log(error)
             })
     }
}
  相关解决方案