我的应用程序具有带<AutoSave/>
组件的表单。表单值更改后,此组件调用将提交。一切正常,但更改路线时,它会更改表单值并<AutoSave/>
调用提交。如何解决这个问题呢?一种可能的解决方案是<AutoSave/>
在更改路线时再次安装。
自动保存:
import React, { useEffect, useCallback } from 'react'
import { useFormikContext } from 'formik'
import debounce from 'lodash.debounce'
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..."}</>
}
我的应用程式:
const App: FC = () => {
const {books} = getBooks() // [{id: 1, title: 'test', summary: 'test'}, ...]
const {query} = useRouter()
const handleSubmit = useCallback(async values => {
try {
await API.patch('/books', {id: query.book, ...values})
} catch (e) {}
}, [query.book])
return (
<>
<span>Books</span>
{books.map(({id, title}, key) => (
<Link key={key} href='/book/[book]' as={`/book/${id}`}>
<a>{title}</a>
</Link>
))}
{query.book && (
<MainForm
book={books.find(book => book.id === query.book)}
handleSubmit={handleSubmit}/>
)}
</>
)
}
MainForm:
type Props = {
book: BookProps // {id: string, title: string ...},
handleSubmit: (values) => Promise<void>
}
const MainForm: FC<Props> = ({book, handleSubmit}) => (
<Formik
enableReinitialize
initialValues={{title: book.title, summary: book.summary}}
handleSubmit={values => handleSubmit(values)}>
{() => (
<Form>
//...My fields...
<AutoSave debounceMs={500}/> // <=== AutoSave with debounce
</Form>
)}
</Formik>
)