P粉2835590332023-08-18 15:20:03
You need to set enableReinitialize
to allow Formik to update the value when it changes.
const form = useFormik({ initialValues: ..., enableReinitialize: true //<-- 这里 });
You can also set the value directly at one time in useEffect
.
useEffect(() => { if (projectData && .../*其他条件*/) { form.setValues(projectData) } }, [projectData])
P粉1762037812023-08-18 12:57:56
If the structure of the data received from the API matches the structure of the form, you can use the setValues
method to set the entire state at once.
Make sure the data structure from the API response (projectData
) matches the structure of your initialValues
.
Use the setValues
method to update all values at once.
const form = useFormik({ initialValues: { name: "", login: "", about: { age: "", rank: { silver: true, gold: false, global: false } } } }); const { setValues } = form; useEffect(() => { if (projectData) { setValues(projectData); } }, [projectData]); // 设置来自API的响应