gpt4 book ai didi

javascript - 如何防止第一次重新渲染 Formik

转载 作者:行者123 更新时间:2023-11-30 19:03:35 26 4
gpt4 key购买 nike

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

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>

最佳答案

嗯,我没有得到一个正常的想法。决定使用带钩子(Hook)的标志 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>
}

有什么改进的想法吗?

关于javascript - 如何防止第一次重新渲染 Formik,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com