React|Rest API: Storing form data into an object o

2019-08-25 11:33发布

问题:

I've set up a react web application that's currently listing all "Employees" from a mongodb.

I'm now trying to "add" employees to the database through a react frontend form.

I've managed to pass the data from the form to the application but I'm unsure of the process I need to go through to actually get that data solidified into an object and stored in the api.

Please excuse my code, it's disgusting as this is my first week learning react(honestly with little js knowledge, that's another story) and I've just patched together like 20 tutorials....

Here's my Form class:

class Form extends React.Component {
  state = {
    fullname: '',
  }

  change = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  onSubmit = e => {
    e.preventDefault();
    this.props.onSubmit(this.state)
    this.setState({
      fullname: ''
    })
  }

  render() {
    return <div>
      <form>
        <input name="fullname" placeholder="Full Name" value={this.state.fullname} onChange={e => this.change(e)} />
        <button onClick={e => this.onSubmit(e)}>Submit</button>
      </form>
    </div>
  }

}

and my Listing(?) class:

class EmployeeList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {employee: []};
    this.EmployeeList = this.EmployeeList.bind(this)
    this.componentDidMount = this.componentDidMount.bind(this)
  }

  componentDidMount() {
    this.EmployeeList();
  }

  EmployeeList() {
    fetch('/api/employees').then(function(data){
      return data.json();
    }).then( json => {
      this.setState({
        employee: json
      });
      console.log(json);
    });
  }

  onSubmit = fields => {
    console.log('app component got: ', fields)

  }

  render() {
    //return a mapped array of employees
    const employees = this.state.employee.map((item, i) => {
      return <div className="row">
        <span className="col-sm-6">{item.fullname}</span>
        <span className="col-sm-2" id={item.action1}></span>
        <span className="col-sm-2" id={item.action2}></span>
        <span className="col-sm-2" id={item.action3}></span>
      </div>
    });

    return <div>
      <Form onSubmit={fields => this.onSubmit(fields)}/>
      <div className="container">
        <div className="row">
        <div className="col-sm-6 bg-warning"><h3>Full Name</h3></div>
        <div className="col-sm-2 bg-success"><h3>Action 1</h3></div>
        <div className="col-sm-2 bg-success"><h3>Action 2</h3></div>
        <div className="col-sm-2 bg-success"><h3>Action 3</h3></div>
      </div>
      </div>



      <div id="layout-content" className="layout-content-wrapper">
        <div className="panel-list">{ employees }</div>
      </div>

    </div>
  }
}

I've managed to pass the data to the listing app evident by

onSubmit = fields => {
    console.log('app component got: ', fields)
}

But how can I go about making a post request to store this data I send into an object on the db? And then also reload the page so that the new list of all employee's is shown?

Thanks so much for your time!

回答1:

You can use fetch API to make POST request as well. Second parameter is the config object wherein you can pass the required request configurations.

fetch('url', {
  method: 'post',
  body: JSON.stringify({
      name: fields.fullname
  })
})
.then(response) {
  response.json();
}
.then( json => {
  this.setState({
    employee: json
  });
});

Additional Request Configs which can be used :

  • method - GET, POST, PUT, DELETE, HEAD
  • url - URL of the request
  • headers - associated Headers object
  • referrer - referrer of the request
  • mode - cors, no-cors, same-origin
  • credentials - should cookies go with the request? omit, same-origin
  • redirect - follow, error, manual
  • integrity - subresource integrity value
  • cache - cache mode (default, reload, no-cache)