简体   繁体   English

React + Formik - 如何传入新值并将表单设置为脏?

[英]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:我正在寻找的是:

  • A way to pass in these new values as something other than initialState (ie somehow imperatively set values from outside <Formik /> ) that would cause dirty to be computed as true一种将这些新值作为initialState以外的东西传递的方法(即以某种方式强制设置来自外部<Formik />的值),这会导致dirty被计算为真
  • A way to force my form to be dirty (it's a read-only property, but if there is another way to mimic it and force it to be true)一种强制我的表单变脏的方法(它是一个只读属性,但如果有另一种方法可以模仿它并强制它为真)
       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);
        }}

Have you tried using the onReset property?您是否尝试过使用onReset属性? That should allow you to pass values from any source you want.这应该允许您从任何您想要的来源传递值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM