繁体   English   中英

交换或删除组时,React Hook Form 值不会改变

[英]React Hook Form value is not changing when swapping or Deleting Groups

我正在制作一个动态的嵌套表单生成器。

这是我正在处理的当前项目: https://codesandbox.io/s/ava-dynamic-react-hook-form-ivgt40?file=/src/App.js

我遇到的问题是,当我交换或删除组时,组内的值设置不正确。

我相信这是由于 {...register()} 和输入组件上的更改 ref 造成的,但我不确定。

顶部链接项目中的表单 data.js 文件包含我希望呈现的表单结构。

list: {
    id,
    label,
    control: "list" // identifier that this element is a list
    creatable: boolean,
    items: [
        [elements], // group 1
        [elements], // group 2
    ]
}
input: {
    id,
    label,
    control: "input" // identifier that this element is a input
    type: "text" // type of input
    defaultValue,
    rules: {
        required: {
            value: boolean,
            message: string,
        }
    }
}

State 管理

您似乎正在混合跟踪 state 的地方。

你基本上有 2 种类型的 state

  • 表格值的 State | 这存储在react-hook-form
  • State 表单输入的排序顺序| 这存储在您的Element.jsx

通过混合这些,您必须手动确保它们保持同步

反应挂钩形式

当你使用react-hook-form时。 您将一些 state 管理委托给该挂钩。 他们通过寄存器提供 API 以跟踪表单的字段和值。

Register 将名称作为第一个参数。
这是表单识别字段的唯一句柄。
新名称将是新字段。

问题

你没有保持同步。
改变顺序会做几件事:

  • 当前的elementIdPath类似于Emailprofile.0.notifications.0.email.0.email-abcd123
  • Emailprofile.0.notifications.0.email.0.email-abcd123作为名称传递给寄存器。
  • 单击更改订单按钮
  • handleSwapListElements运行并通过setElementItem更改元素
  • elementIdPath更改: Emailprofile.0.notifications.0.email.1.email-abcd123 (通知索引从 0 更改为 1)
  • 注册新名称并将其视为新字段
  • 旧字段也仍然在 state 中注册。单击提交也将具有旧名称和值。

修复

保持排序顺序和值同步。 你必须自己决定具体怎么做。 任何一个:

  • 不要在名称中包含排序顺序或索引作为键。
  • 使用react-hook-form方法手动保持同步。

两者都有起伏。

不包括索引作为键

没有索引的动态表单将要求您将所有信息附加到字段本身。 基本上,您会注册一个唯一密钥 (uuid),并自己跟踪 uuid 路径。
IE你注册到属性:

 {
   "abcd123-value" : "some@email.de",
   "abcd123-path"  : "Emailprofile.0.notifications.0.email.0.email-abcd123" // this would not be shown to the user, but still exposed to the form, in the submit you would manually combine the information again. 
 }

使用react-hook-form方法手动保持同步。

每当您更改字段name时,您将获得当前值。 注销旧名称并在新名称上设置值。
react-hook-form公开了一个钩子方法。

注销设置值

如果由我决定,并查看您的代码。我可能会朝这个方向尝试 go,而不是重构事物以从名称中删除索引。

沙箱

这个经过修改的沙箱应该可以描绘出画面。 对于基本元素,它还不能正常工作,但是profile.0.notification.0.email中的节点应该是 function。

暂无
暂无

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

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