[英]react axios post generates json in array format. How to convert this to “name”:“value” type format
const submitService = {
serviceType: this.state.serviceType,
dateOfService: this.state.dateOfService,
vehicleId: this.state.vehicleId,
orderNum: this.state.orderNum,
driverId: this.state.driverId,
vendorName: this.state.vendorName,
issueId: this.state.issueId
};
axios.post("http://localhost:8072/TruckyServiceMicroService/admin/services/saveService/", submitService)
.then(response => {
if (response.data != null) {
this.setState(this.initialState);
alert("Service Created Successfully");
}
});
這是構成 json 的 const 和使用 const 發送的 post 請求。 通過 axios 發送 post 請求時,它在 json 中添加方括號
initialState = {
serviceType: [], vehicleId: '', dateOfService: '', orderNum: '', driverId: '', vendorName: '', issueId: ''
}
這是 state
如果您想快速修復,請更改:
const submitService = {
serviceType: this.state.serviceType,
dateOfService: this.state.dateOfService,
vehicleId: this.state.vehicleId,
orderNum: this.state.orderNum,
driverId: this.state.driverId,
vendorName: this.state.vendorName,
issueId: this.state.issueId
};
至:
const keys = ["serviceType","dateOfService","vehicleId","orderNum","driverId","vendorName","issueId"]
const submitService = Object.entries(this.state).reduce((res, ([key, val])) => {
if(keys.includes(key))
res[key] = Array.isArray(val)?val[0]:val
return res
}, {})
這基本上使用 state 的鍵和值對創建有效負載,但如果值是數組類型,它只使用它的第一個索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.