问题描述
在以下代码中显示提交功能,在以下代码中显示我要在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)
})
}
1楼
不要使用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)
})
}
}