Json 如何从React表单提交中排除字段?
我使用的是React 16.13.0。我有一个FormContainer组件,它可以构造它的数据并像这样呈现它Json 如何从React表单提交中排除字段?,json,reactjs,forms,components,Json,Reactjs,Forms,Components,我使用的是React 16.13.0。我有一个FormContainer组件,它可以构造它的数据并像这样呈现它 class FormContainer extends Component { statics: { DEFAULT_COUNTRY: 484; } constructor(props) { super(props); this.state = { countries: [], provinces: [], n
class FormContainer extends Component {
statics: {
DEFAULT_COUNTRY: 484;
}
constructor(props) {
super(props);
this.state = {
countries: [],
provinces: [],
newCoop: {
name: '',
type: {
name: ''
},
address: {
formatted: '',
locality: {
name: '',
postal_code: '',
state: ''
},
country: 484, //FormContainer.DEFAULT_COUNTRY,
},
enabled: true,
email: '',
phone: '',
web_site: ''
},
...
render() {
return (
<form className="container-fluid" onSubmit={this.handleFormSubmit}>
<Input inputType={'text'}
title= {'Name'}
name= {'name'}
value={this.state.newCoop.name}
placeholder = {'Enter cooperative name'}
handleChange = {this.handleInput}
/> {/* Name of the cooperative */}
<Input inputType={'text'}
title= {'Type'}
name= {'type.name'}
value={this.state.newCoop.type.name}
placeholder = {'Enter cooperative type'}
handleChange = {this.handleInput}
/> {/* Type of the cooperative */}
...
<Country title={'Country'}
name={'address.country'}
options = {this.state.countries}
value = {this.state.newCoop.address.country}
placeholder = {'Select Country'}
handleChange = {this.handleInput}
/> {/* Country Selection */}
...
问题是,我想排除提交内容的“country”属性,因为服务器不需要/不接受该字段。如何提交表单,将该字段排除在外,同时将其保留为添加数据的字段?一种方法是创建一个对象,使用
delete
操作符从该对象中删除国家/地区密钥,并将该对象传递给服务器
handleFormSubmit(e) {
e.preventDefault();
let NC = this.state.newCoop;
delete NC.address.country;
fetch('http://localhost:9090/coops/',{
method: "POST",
body: JSON.stringify(NC),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
response.json().then(data =>{
console.log("Successful" + data);
})
})
}
handleFormSubmit(e) {
e.preventDefault();
let NC = this.state.newCoop;
delete NC.address.country;
fetch('http://localhost:9090/coops/',{
method: "POST",
body: JSON.stringify(NC),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
response.json().then(data =>{
console.log("Successful" + data);
})
})
}