我有一个从后端获取的数据:
fetchUserData = async () => {
...fetching data
this.setState({
username: resp.data.data.uname
});
}
我希望 Formik 验证后端保存的数据,所以我向 Formik 组件添加了enableReinitialize:
<Formik
initialValues={{
username: this.state.username,
password: this.state.password,
confirmPassword: this.state.confirmPassword
}}
validationSchema={this.schema}
enableReinitialize
>
但问题是这样的,它现在重置了触摸的道具值:
谢谢。
重新初始化后无法保留触摸状态。 我们必须实施一种解决方法来备份
touched
对象并使用 initialTouched
来恢复它。
https://formik.org/docs/api/formik#initialtouched-formiktouchedvalues
或者,如果您不想每次状态值更改时都重置表单,请放弃
enableReinitialize
标志。
您可以根据您的用例,在适当的时间使用 Formik innerRef
手动调用 resetForm()
或 setFieldValue()
。
import { useRef } from "react";
import { Formik } from "formik";
const formRef = useRef();
<Formik
innerRef={formRef} // <--- add this
// enableReinitialize <--- remove this
initialValues={{
username: this.state.username, // now, state changes will not auto reflect in your form
password: this.state.password,
confirmPassword: this.state.confirmPassword,
}}
validationSchema={this.schema}
>
import { useEffect } from "react";
// reset form only when you really need to re-initialize the form
useEffect(() => {
const { username, password, confirmPassword } = defaultStates;
formRef.current.resetForm({
username: username,
password: password,
confirmPassword: confirmPassword,
});
}, [someTrigger]);
// listen to your state changes and update the field accordingly
useEffect(() => {
formRef.current.setFieldValue("username", this.state.username);
// or, even modify the touched flag
formRef.current.setFieldTouched("username", false);
}, [this.state.username]);