如何防止第一次重新提交Formik

时间:2019-12-07 21:36:20

标签: javascript reactjs typescript forms formik

我开始使用by Jared Palmer创建的<AutoSave/>组件:

const AutoSave = ({debounceMs}) => {
  const formik = useFormikContext()

  const debouncedSubmit = useCallback(
    debounce(formik.submitForm, debounceMs),
    [formik.submitForm, debounceMs]
  )

  useEffect(() => debouncedSubmit, [debouncedSubmit, formik.values])

  return <>{!!formik.isSubmitting && 'saving...'}</>
}

主要问题是当我进入页面时,<AutoSave/>在页面安装后提交表单,如何防止这种行为?

示例:

<Formik onSubmit={values => callMyApi(values)} initialValues={{bla: 'bla-bla'}}>
  {() => (
    //...My beautiful field components...
    <AutoSave debounceMs={300}/>
  )}
</Formik>

1 个答案:

答案 0 :(得分:1)

好吧,我没有一个正常的主意。决定使用带有钩子usePrevious的标志:

import {useRef} from 'react'

const usePrevious = value => {
  const ref = useRef()
  const prev = ref.current
  ref.current = value
  return prev
}

现在看起来像:

const MyForm = () => {
  const [shouldUpdate, setShouldUpdate] = useState(false)
  const previousShouldUpdate = usePrevious(shouldUpdate)

  useEffect(() => {
    setShouldUpdate(true)
    return () => {setShouldUpdate(false)}
  }, [])

  <Formik onSubmit={values => {
    if (previousShouldUpdate) {
      return callMyApi(values)
    }
  }} initialValues={{bla: 'bla-bla'}}>
    {() => (
      //...My beautiful field components...
      <AutoSave debounceMs={300}/>
    )}
  </Formik>
}

有什么更好的想法吗?