如何使用Redux Form和Express处理POST请求?

时间:2016-04-20 14:51:20

标签: javascript redux redux-form

当您使用普通的HTML表单并提交POST请求时,该请求将被发送到快速发布路径,如下所示:

app.post('/api/items', function(req, res) {
  // req from HTML form
});

但是当您使用Redux Forms并且您正在向API发出POST请求时,该请求是否会以相同的方式作为后期路径中的请求传递?

1 个答案:

答案 0 :(得分:1)

使用Redux表单时,表单不会像经典HTML表单一样提交。相反,会触发回调(默认为onSubmit)以提交数据。

考虑以下形式:

reduxForm({
  form: "form",
  fields: ["foo", "bar"],
})(
  class MyForm extends Component {
    render() {
      return (
        <form onSubmit={this.props.handleSubmit}>
          <input type="text" {...this.props.fields.foo} />
          <input type="text" {...this.props.fields.bar} />
          <button>{"Save"}</button>
        </form>
      )
    }
  }
)

您可以通过以下方式将表单值发布到/api/items

<MyForm onSubmit={
  values => new Promise((resolve, reject) => {
    fetch("/api/items", {method: "post", body: JSON.stringify(values)})
      .then(res => res.json())
      .then(res => {
        if (res.hasOwnProperty("errors")) {
          reject(res.errors)
        } else {
          resolve(res.data)
        }
      })
  })
} />
相关问题