【问题标题】:Check if input has the same value React检查输入是否具有相同的值 React
【发布时间】: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


【解决方案1】:

如果您在 handleSubmit 函数中更改窗口位置,则无需担心未来的状态。你可以使用 dirty 传入 render prop 的 prop,如下所示:

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 以某种形式,无论是像您在此处所做的本地一样,还是全局.

希望对你有帮助。

【讨论】:

  • 嗨! window.location.href 实际上是作为示例编写的。一般来说,我同意你的回答!
  • 嗨!我很高兴它有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2015-06-30
  • 2019-05-04
  • 2012-07-01
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多