在JSON.Stringify中将一些数据从fetch数组传递到int



我尝试POST数据到服务器。我的问题是,我得到错误'422(不可处理的实体)',因为数据都在字符串,所以我需要将一些数据转换为int。如何将一些数据转换为int从数组绑定到其他参数之前?我需要转换一些数据,其中涉及& &;

class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
alldata: [],
singledata: {
invono: "",
invodate: "",
lotno: "",
buildup: "",
custid: "",
},
};

createInvoice() {
fetch("http://xxx:8081/invoice", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify(this.state.singledata),
//JSON.parse(JSON.stringify(this.state.singledata)),
// JSON.stringify({this.state.singledata : parseInt($({this.state.singledata.invono}).val(),10)})
}).then(
this.setState({
singledata: {
invono: "",
invodate: "",
lotno: "",
buildup: "",
custid: "",
},
})
);
}

处理用户输入。

handleChange(event) {
var invono = this.state.singledata.invono;
var invodate = this.state.singledata.invodate;
var lotno = this.state.singledata.lotno;
var buildup = this.state.singledata.buildup;
var custid = this.state.singledata.custid;
if (event.target.name == "invono") invono = event.target.value;
else if (event.target.name == "invodate") invodate = event.target.value;
else if (event.target.name == "lotno") lotno = event.target.value;
else if (event.target.name == "buildup") buildup = event.target.value;
else if (event.target.name == "custid") custid = event.target.value;
this.setState({
singledata: {
invono: invono,
invodate: invodate,
lotno: lotno,
buildup: buildup,
custid: custid,
},
});
}

使用parseInt作为数字字段

handleChange(event) {
const fieldname = event.target.name;
// put in the names of the fields that need to be converted to integers into
// the array below
const convertToInts = ["invono", "lotno"];
const value = convertToInts.includes(fieldname) ? parseInt(event.target.value, 10) : event.target.value;
this.setState({
...this.state,
singledata: {
...this.state.singledata,
[fieldname]: value,
},
});
}

最新更新