您如何在 Formik 中验证提交时的 http 请求?
How do you validate http requests on submit in Formik?
据我所知,提交事件仅适用于一些静态检查,例如 Yup 或其他。
我真正需要的是执行类似 /product/store
的请求,如果从服务器收到任何错误,则将其显示在表单上。
出于逻辑原因,我无法在验证方法中提出该请求,因为...它不是提交。我希望 submit 发出 /product/store
请求,如果失败则设置错误字段。
我的假设是 validactionSchema 和 validate 方法仅用于静态检查,如正则表达式匹配。
formik 文档中的示例具有误导性,因为它使用了一些无逻辑的 setTimeout 承诺,但对服务器的实际请求具有其含义并且应该在提交时进行。
没有 redux 顺便说一句。
假设您的服务器的响应包含错误,您可以使用 setFieldError
函数为字段设置错误。
下面的代码假定服务器 returns 一个错误状态代码,其响应包含以下格式的错误 [{"field":"name","message":"Name cannot be empty."}]
。
const handleSubmit = (values, actions) => {
makeSomePostRequest(values)
.then(response => console.log('success!'))
.catch(error => {
/* If your server returns something like a 422 when the
validation fails it will move to the catch part. Here
you can use the actions.setFieldError to set the errors
in your form.
*/
error.response.data.forEach(error => {
actions.setFieldError(error.field, error.message)
})
})
.finally(() => actions.setSubmitting(false))
}
据我所知,提交事件仅适用于一些静态检查,例如 Yup 或其他。
我真正需要的是执行类似 /product/store
的请求,如果从服务器收到任何错误,则将其显示在表单上。
出于逻辑原因,我无法在验证方法中提出该请求,因为...它不是提交。我希望 submit 发出 /product/store
请求,如果失败则设置错误字段。
我的假设是 validactionSchema 和 validate 方法仅用于静态检查,如正则表达式匹配。
formik 文档中的示例具有误导性,因为它使用了一些无逻辑的 setTimeout 承诺,但对服务器的实际请求具有其含义并且应该在提交时进行。
没有 redux 顺便说一句。
假设您的服务器的响应包含错误,您可以使用 setFieldError
函数为字段设置错误。
下面的代码假定服务器 returns 一个错误状态代码,其响应包含以下格式的错误 [{"field":"name","message":"Name cannot be empty."}]
。
const handleSubmit = (values, actions) => {
makeSomePostRequest(values)
.then(response => console.log('success!'))
.catch(error => {
/* If your server returns something like a 422 when the
validation fails it will move to the catch part. Here
you can use the actions.setFieldError to set the errors
in your form.
*/
error.response.data.forEach(error => {
actions.setFieldError(error.field, error.message)
})
})
.finally(() => actions.setSubmitting(false))
}