问题:
如果值未更改,如何防止提交?
我尝试使用useState
来做到这一点。
代码段:
import React from 'react'
import {Formik, Form, Field} from 'formik'
const Search = () => {
const [searchValue, setSearchValue] = useState('')
const handleSubmit = q => {
window.location.href = `https://for-example.com/search?q=${q}`
}
return (
<Formik onSubmit={({q}, {setSubmitting}) => {
setSubmitting(false)
setSearchValue(q) // <===
return q !== searchValue && handleSubmit(q) // <===
}} initialValues={{q: ''}} render={() => (
<Form>
<Field name='q' />
</Form>
)}/>
)
}
P.S。。此方法有效,但我认为不值得为此简单任务创建useState
。我可以用其他方式检查搜索值吗?
答案 0 :(得分:3)
如果您要在handleSubmit
函数中更改窗口位置,则无需担心将来的状态。您可以使用在渲染道具中传递的dirty
道具,如下所示:
import React from 'react'
import {Formik, Form, Field} from 'formik'
const Search = () => {
const handleSubmit = q => {
window.location.href = `https://for-example.com/search?q=${q}`
}
return (
<Formik onSubmit={({q}, {setSubmitting}) => {
setSubmitting(false)
handleSubmit(q)
}} initialValues={{q: ''}} render={({ dirty, handleSubmit, isSubmitting }) => (
<form onSubmit={handleSubmit}>
<Field name='q' />
<button type="submit" disabled={!dirty || isSubmitting}>
Submit
</button>
</form>
)}/>
)
}
如果您不更改提交时的位置,或者出于任何其他原因可以多次提交同一表格(具有不同的值),则您需要以某种形式state
(像在此一样本地)或全局。
希望有帮助。