我在反应模态中有一个表单可以编辑一个项目。我正在使用道具(来自 firebase 的数据)初始化表单。我希望用户能够编辑字段并单击保存以更新 firebase 中的数据。
更新逻辑正常;但是,当单击保存并提交然后重新打开相同模式时,字段具有旧数据(更新前)。我的目标是在更新 firestore 数据库时更新初始值。初始值不会自动更新(是因为它们作为道具传递了吗?)
这是我的模态组件:
export function Modal({
id,
title,
topLabel,
leftLabel,
rightLabel,
tags,
notes,
open,
setOpen,
}) {
const formFields = {
initialValues: {
title: title,
topLabel: topLabel,
leftLabel: leftLabel,
rightLabel: rightLabel,
tags: tags?.join(", "),
notes: notes,
},
validationSchema: validationSchema,
enableReinitialize: true,
fields: [
// array of input text fields here
],
};
const handleUpdate = async (values) => {
// handle update logic here
};
return (
<ModalContainer
title="Edit item"
open={open}
setOpen={setOpen}
formFields={formFields}
onSubmit={handleUpdate}
buttonLabel="Save"
/>
);
};
ModalContainer
组件中与formik相关的逻辑是:
const formik = useFormik({
initialValues: formFields.initialValues,
validationSchema: formFields.validationSchema,
enableReinitialize: formFields.enableReInitialize,
onSubmit: async (values, actions) => {
try {
setOpen(false);
await onSubmit(values, actions);
} catch (error) {
setOpen(false);
console.error(error);
}
},
});
useEffect(() => {
formik.setTouched({}, false);
formik.resetForm();
}, [open]);
我做错了什么?如何解决这个问题?