表单提交

提交阶段

¥Submission Phases

要在 Formik 中提交表单,你需要以某种方式触发提供的 handleSubmit(e)submitForm 属性。当你调用这两个方法中的任何一个时,Formik 每次都会执行以下(伪代码):

¥To submit a form in Formik, you need to somehow fire off the provided handleSubmit(e) or submitForm prop. When you call either of these methods, Formik will execute the following (pseudo code) each time:

预提交

¥Pre-submit

  • 触摸所有字段。initialValues 是必需的并且应始终指定。参见 #445

    ¥Touch all fields. initialValues are required and should always be specified. See #445

  • isSubmitting 设置为 true

    ¥Set isSubmitting to true

  • 增量 submitCount + 1

    ¥Increment submitCount + 1

验证

¥Validation

  • isValidating 设置为 true

    ¥Set isValidating to true

  • 异步运行所有字段级验证、validatevalidationSchema 并深度合并结果

    ¥Run all field-level validations, validate, and validationSchema asynchronously and deeply merge results

  • 有没有错误?

    ¥Are there any errors?

    • 是的:中止提交。设置 isValidatingfalse、设置 errors、设置 isSubmittingfalse

      ¥Yes: Abort submission. Set isValidating to false, set errors, set isSubmitting to false

    • 不:将 isValidating 设置为 false,继续进行 "提交"

      ¥No: Set isValidating to false, proceed to "Submission"

提交

¥Submission

  • 继续运行提交处理程序(即 onSubmithandleSubmit

    ¥Proceed with running the submission handler (i.e. onSubmit or handleSubmit)

  • 提交处理程序是否返回了 promise?

    ¥Did the submit handler return a promise?

    • 是的:等到解决或拒绝,然后将 setSubmitting 设置为 false

      ¥Yes: Wait until it is resolved or rejected, then set setSubmitting to false

    • 不:调用 setSubmitting(false) 完成循环

      ¥No: Call setSubmitting(false) to finish the cycle

常见问题

¥Frequently Asked Questions

How do I determine if my submission handler is executing?

如果 isValidatingfalseisSubmittingtrue

¥If isValidating is false and isSubmitting is true.

Why does Formik touch all fields before submit?

通常的做法是仅在已访问过输入时才在 UI 中显示输入错误(也称为 "touched")。在提交表单之前,Formik 会触摸所有字段,以便所有可能已隐藏的错误现在都将可见。

¥It is common practice to only show an input's errors in the UI if it has been visited (a.k.a "touched"). Before submitting a form, Formik touches all fields so that all errors that may have been hidden will now be visible.

How do I protect against double submits?

如果 isSubmittingtrue,则禁用触发提交的任何内容。

¥Disable whatever is triggering submission if isSubmitting is true.

How do I know when my form is validating before submit?

如果 isValidatingtrueisSubmittingtrue

¥If isValidating is true and isSubmitting is true.

Why does `isSubmitting` remain true after submission?

如果提交处理程序返回一个 promise,请确保在调用时正确解决或拒绝它。

¥If the submission handler returns a promise, make sure it is correctly resolved or rejected when called.

如果提交处理程序不返回 promise,请确保在处理程序末尾调用 setSubmitting(false)

¥If the submission handler does not return a promise, make sure setSubmitting(false) is called at the end of the handler.

Formik 中文网 - 粤ICP备13048890号