在 useFieldArray 中编辑单个项目
Editing single item in useFieldArray
我正在使用并喜爱 react-hook-form
。我 运行 遇到了一个问题,我有一个项目列表(假设在左栏中),然后当您单击任何项目时,它会在右栏中显示所选项目的编辑组件。问题是当我在项目之间切换时,嵌套数组值 似乎没有正确更新数据。
我想我明白,因为没有为每个父项创建一个新的编辑组件(我只是向下传递选定的索引)编辑组件中的嵌套 useFieldArray
仍然引用第一个父项物品。如果是这样的话,我不确定如何确保为每个被选中的项目创建一个新的 useFieldArray
。
这是一个复制问题的代码箱:
https://codesandbox.io/s/dreamy-brattain-r74lx
非常感谢任何帮助。
我认为您可以在 <Details />
组件内映射您观看的 item
的 childItems
道具,而不是使用 fields
。当您使用 watch
时,<Details />
将在添加新的子项目后重新呈现。
如果您的 <Details />
组件应该变得更复杂,我也建议在这里使用 useWatch
而不是传递 watch
。在 useWatch
:
的文档中查看此引用
Behaves similarly to the watch API, however, this will isolate
re-rendering at the component level and potentially result in better
performance for your application.
这是一个使用 useWatch
的例子:
我正在使用并喜爱 react-hook-form
。我 运行 遇到了一个问题,我有一个项目列表(假设在左栏中),然后当您单击任何项目时,它会在右栏中显示所选项目的编辑组件。问题是当我在项目之间切换时,嵌套数组值 似乎没有正确更新数据。
我想我明白,因为没有为每个父项创建一个新的编辑组件(我只是向下传递选定的索引)编辑组件中的嵌套 useFieldArray
仍然引用第一个父项物品。如果是这样的话,我不确定如何确保为每个被选中的项目创建一个新的 useFieldArray
。
这是一个复制问题的代码箱:
https://codesandbox.io/s/dreamy-brattain-r74lx
非常感谢任何帮助。
我认为您可以在 <Details />
组件内映射您观看的 item
的 childItems
道具,而不是使用 fields
。当您使用 watch
时,<Details />
将在添加新的子项目后重新呈现。
如果您的 <Details />
组件应该变得更复杂,我也建议在这里使用 useWatch
而不是传递 watch
。在 useWatch
:
Behaves similarly to the watch API, however, this will isolate re-rendering at the component level and potentially result in better performance for your application.
这是一个使用 useWatch
的例子: