簡體   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