我正在尝试以动态形式实现列表发布 API,但我无法在此处正确以动态形式发布数据,这是我所做的所有代码。当我从表单发送发布请求时,所有数据都会显示,但仅奖品列表项未显示我尝试使用映射,但我仍然可以解决我的问题,请指导我哪里做错了
import React, { Component } from "react";
import { Helmet } from "react-helmet";
import Form from "./Form";
import Additional from "./Additional";
import Prize from "./Prize";
import Swal from "sweetalert2";
import axios from "axios";
import { withTranslation } from "react-i18next";
class Create extends Component {
constructor(props) {
super(props);
this.state = {
isHidden: true,
title: "",
lead: "",
span: "",
without: "",
startDate: null,
endDate: null,
parameter: "",
prizes: [
{
number_list: [],
prize_type: "",
name: "",
value: null,
quantity: ""
}
]
};
this.handleSubmit = this.handleSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.toggleHie = this.toggleHie.bind(this);
}
async onChange(event) {
await this.setState({
[event.target.name]: event.target.value
});
console.log(this.state);
}
handleSubmit(e) {
let authToken = localStorage.getItem("Token");
e.preventDefault();
const data = {
title: this.state.title,
lead: this.state.lead,
span: this.state.span,
startDate: this.state.startDate,
endDate: this.state.endDate,
parameter: this.state.parameter,
prizes: [
this.state.prizes.map(c => {
c.number_list = c.number_list;
c.prize_type = c.prize_type;
c.name = c.name;
c.value = c.value;
c.quantity = c.quantity;
})
]
};
axios({
method: "post",
url: `https://digitalfleet.eu/api/1/campaigns/`,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + JSON.parse(authToken)
},
data
})
.then(res => {
this.setState({
title: "",
lead: "",
span: "",
startDate: "",
endDate: "",
parameter: "",
prizes: [
{
number_list: [],
prize_type: "",
name: "",
value: null,
quantity: ""
}
]
});
this.props.history.push("/createcampaign");
Swal.fire({
title: "Campaign",
type: "success",
text: " Added Successfully !",
showConfirmButton: false,
timer: 2000
});
})
.catch(err => {
console.log(err);
Swal.fire({
title: "Campaign",
type: "error",
text: "Error while Creating new!",
timer: 2000
});
});
}
最佳答案
Javascript map 返回一个数组,因此您不需要像您那样将 data.prizes 定义为数组。
你能像这样构造你的数据对象并尝试吗?
const {title, lead, span, startDate, endDate, parameter, prizes} = this.state;
const data = {title, lead, span, startDate, endDate, parameter, prizes};
关于javascript - ReactJs-如何为每个列表 Axios post 方法进行映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60094681/