在final-form-arrays中为数组提供initialValues会导致状态更改以重置整个表单,我该如何防止呢? [英] Providing initialValues for an array in final-form-arrays causes state changes to reset the whole form, how can i prevent this?

查看:60
本文介绍了在final-form-arrays中为数组提供initialValues会导致状态更改以重置整个表单,我该如何防止呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用final-form-arrays的表单.表单有效且验证有效,但是,当我在组件内部进行状态更改时,它将重置我的所有值.

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.

我能够使用react-final-form-arrays提供的示例来复制该问题:

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

我添加了一个按钮来切换状态更改.本质上,只需尝试填写表单中的值,然后更改状态即可.表格将重置,我不知道为什么会这样.如果我删除initialValues,这不会发生.

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?

推荐答案

2个问题.

  1. 您要将一个内联renderProp传递给Form组件,这意味着它在每次渲染组件时都会创建一个新函数,这会导致您的表单重置.解决方案是将renderProp移至上方的函数中并传入,理想情况下使用useCallback进行记忆.
  2. 修复以上问题后,表格仍将重置.这是因为您要将内联数组传递给initialValues.每次您的组件渲染时,这将再次创建一个新数组,这将重置您的表单.将其移入变量并传递.

这是一个非常常见的初学者错误,您应该阅读有关参考相等性检查如何反应以找出要重新渲染哪些组件的信息.

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.

固定版本: https://codesandbox.io/embed/react-final-form-field-arrays-c6hgu

这篇关于在final-form-arrays中为数组提供initialValues会导致状态更改以重置整个表单,我该如何防止呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆