簡體   English   中英

反應 axios 后以數組格式生成 json。 如何將其轉換為“名稱”:“值”類型格式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM