【发布时间】:2020-02-03 04:27:30
【问题描述】:
问题:
如果值没有改变,如何防止提交?
我尝试使用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。我可以通过其他方式检查搜索值吗?
【问题讨论】:
-
这是 React 的做事方式
-
@Andrew,是的,问这个问题可能很奇怪,但我会等待答案
标签: javascript html reactjs forms formik