[英]How do I exclude a field from my React form submission?
我正在使用 React 16.13.0。 我有一个 FormContainer 组件,它构建其数据并像这样呈现它......
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 */}
...
它具有以下提交逻辑...
handleFormSubmit(e) {
e.preventDefault();
fetch('http://localhost:9090/coops/',{
method: "POST",
body: JSON.stringify(this.state.newCoop),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
response.json().then(data =>{
console.log("Successful" + data);
})
})
}
问题是,我想排除正在提交的内容的“国家/地区”属性,因为服务器不需要/接受该字段。 如何提交不包括该字段的表单,同时将其保留为添加数据的字段?
一种方法是创建一个对象,使用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);
})
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.