React | Rest API:将表单数据存储到REST API上的对象中 [英] React|Rest API: Storing form data into an object on the REST API

查看:115
本文介绍了React | Rest API:将表单数据存储到REST API上的对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个React Web应用程序,该应用程序当前列出了mongodb中的所有雇员".

我现在正试图通过反应前端表单将员工添加"到数据库中.

我已经设法将数据从表单传递到应用程序,但是我不确定要实际将数据固化为对象并存储在api中的过程.

请原谅我的代码,这很令人讨厌,因为这是我第一周的学习反应(老实说,只有很少的js知识,这是另一个故事),我已经像20个教程一样将它们拼凑在一起了.

这是我的Form课:

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>
  }

}

和我的Listing(?)类:

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>
  }
}

我已经成功地将数据传递到了

所示的列表应用中

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

但是我该如何发出发布请求以存储发送到db对象中的数据呢?然后重新加载页面,以便显示所有员工的新列表吗?

非常感谢您的时间!

解决方案

您也可以使用访存API发出POST请求.第二个参数是config对象,您可以在其中传递所需的请求配置.

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

可以使用的其他请求配置:

  • 方法-GET,POST,PUT,DELETE,HEAD
  • url-请求的URL
  • 标题-关联的标题对象
  • 引荐来源网址-请求的引荐来源网址
  • 模式-cors,no-cors,同源
  • 凭证-cookie是否应与请求一起使用?省略,起源相同
  • 重定向-遵循,错误,手动
  • 完整性-子资源完整性值
  • 缓存-缓存模式(默认,重新加载,无缓存)

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!

解决方案

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)

这篇关于React | Rest API:将表单数据存储到REST API上的对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆