如何从我的React表单提交中排除字段?

问题描述 投票:0回答:1

我正在使用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);
        })
    })
  }

问题是,我想排除正在提交的内容的“国家”属性,因为服务器不需要/不接受此字段。如何提交不包含该字段的表单,同时又将其保留为添加数据的字段?

json reactjs forms components
1个回答
0
投票

一种方法是创建一个对象,并使用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);
        })
    })
  }
© www.soinside.com 2019 - 2024. All rights reserved.