服务器响应后重置 Redux-Form

Reset Redux-Form after server response

我正在研究如何在服务器响应 200 成功消息时重置我的表单字段。所有的例子似乎都集中在提交成功时清除字段(不管服务器响应如何)但是我不想在服务器有 400 响应时清除字段。

在我的容器组件中我有:

submit = (data) => {
  axios.post("/path/to/server", data)
    .then((response) => {
      //reset form somehow
    })
    .catch((err) => {
      //keep values in form and show error message
    })
}

然后我使用以下方式呈现表单:

<SubscribeForm onSubmit={this.submit} />

在我的演示组件中,我有:

let MyForm = props => {
  const { handleSubmit } = props;

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email Address:</label>
      <Field name="email" component="input" type="text"/>
      <input type="submit" value="Submit"/>
    </form>
  );
}

// Decorate the form component
MyForm = reduxForm({
  form: 'myForm',
})(MyForm);

您可以使用 "react refs" https://facebook.github.io/react/docs/refs-and-the-dom.html

如果你给你的表单组件添加一个引用,那么你可以调用:

<form ref="formRef" onSubmit={handleSubmit}>
...

this.refs.formRef.reset();

您只需确保可以访问 "this.refs" 或进一步传递它。

redux-form 中,表单状态存储在您的 redux 商店中。因此,重置表单本质上是一种改变该状态的操作。

基于此,我将尝试找到一种方法将表单状态从 the action creators that redux-form passes as props 重置为装饰表单组件。您会方便地找到一个名为 reset.

下一个挑战是如何从 onSubmit 回调中调度 reset 操作。来自 the docs, you can see that onSubmit is passed three arguments: values, dispatch and props. These nicely give us the tools to dispatch the reset action. Additionally you can resolve your fail case with a SubmissionError,这将确保在修饰的表单组件中正确设置与错误相关的道具。例如像这样:

submit = (values, dispatch, props) => {
  axios.post("/path/to/server", values)
    .then((response) => {
      //reset form somehow
      dispatch(props.reset())
    })
    .catch((err) => {
      //keep values in form and show error message
      return new SubmissionError({
        _error: 'Generic submission failed message here!'
      })
    })
}

希望对您有所帮助!