[英]React + Formik - how to pass in new values and set form as dirty?
I have a Formik form in my React app and I have a specific scenario I can't seem to find a workaround for:我的 React 应用程序中有一个 Formik 表单,我有一个特定的场景,我似乎找不到解决方法:
I have a toggle outside of my custom form component that essentially "sets everything in the form to false".我在自定义表单组件之外有一个切换,它基本上“将表单中的所有内容设置为 false”。 My current solution is when that gets toggled, I update the props I'm passing to form component, and re-rendering:
我当前的解决方案是当它被切换时,我更新我传递给表单组件的道具,并重新渲染:
In my Form component:在我的表单组件中:
const [initialState, setInitialState] = useState(props.initialState);
useEffect(() => {
setInitialState(props.initialState);
}, [props.initialState]);
...
...
<Formik
enableReinitialize
initialState={initialState}
...
/>
This does correctly update my form with the new values, but it doesn't set the form to be dirty
.这确实使用新值正确更新了我的表单,但它不会将表单设置为
dirty
。 I have logic in my form component based on whether it is dirty, and in this scenario I want the form to be considered dirty.我的表单组件中有基于它是否脏的逻辑,在这种情况下,我希望表单被认为是脏的。 I first tried to set each field to be
touched
or include each one in initialTouched
.我首先尝试设置要
touched
的每个字段或将每个字段包含在initialTouched
中。 However, dirty
is computed comparing current values to initialState
, not whether fields have been touched, so my form here is considered "pristine" because it is literally the same as my (new) initial state.然而,
dirty
值是通过比较当前值与initialState
来计算的,而不是字段是否被触及,所以我的表单在这里被认为是“原始的”,因为它与我的(新)初始 state 完全相同。
What I'm looking for is either:我正在寻找的是:
initialState
(ie somehow imperatively set values from outside <Formik />
) that would cause dirty
to be computed as trueinitialState
以外的东西传递的方法(即以某种方式强制设置来自外部<Formik />
的值),这会导致dirty
被计算为真 onSubmit={(values, { setSubmitting, resetForm }) => {
setSubmitting(true);
setTimeout(async () => {
console.log(values);
// it will set formik.isDirty to false
// it will also keep new values
resetForm({ values });
}, 100);
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.