Providing initialValues for an array in final-form-arrays causes state changes to reset the whole form, how can i prevent this?

三世轮回 提交于 2021-02-07 19:23:58

问题


I have a form that uses final-form-arrays. The form works and validation works, however, when i make a state change inside the component, it resets all my values.

I was able to replicate the issue with the same example that react-final-form-arrays provides:

https://codesandbox.io/embed/react-final-form-field-arrays-om6p6

I added a button to toggle a state change. Essentially, just try filling values in the form, and then change the state. The form will reset, and i cant figure out why that is the case. If i remove initialValues, this does not happen.

Does anyone know why that may be?


回答1:


2 problems.

  1. You're passing an inline renderProp to the Form component, this means it's creating a new function every time your component renders which causes your form to reset. The solution is to move the renderProp into a function above and pass that in, ideally memoized with useCallback.
  2. Once you fix the above the form will still reset. This is because you're passing an inline array to initialValues. This again will create a new array every time your component renders which resets your form. Move it into a variable and pass it in.

This is a pretty common beginner mistake, you should read up on how react does reference equality checks to figure out which components to re-render.

Fixed version: https://codesandbox.io/embed/react-final-form-field-arrays-c6hgu




回答2:


Just memorize your initialValues in an arrow function then pass it to the form component:

const initialValues = useCallback(() => {
    return {data: [{}]};
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Pass the function as your Form component's initialValues prop.



来源:https://stackoverflow.com/questions/56454736/providing-initialvalues-for-an-array-in-final-form-arrays-causes-state-changes-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!