reactjs - react 钩子(Hook)形式 V7 : value is not cleared after unmounting its registered component

标签 reactjs material-ui react-hook-form

在 V6 中,当我使用 watch 关闭组件时方法,该组件将被卸载,任何依赖于已卸载组件值的同级组件也将被卸载:

例如:

  • 我们有三个组件 <ComponentA /> , <ComponentB /><ComponentC /> .
  • 何时 <ComponentA />等于"is",<ComponentB/>已渲染。
  • 何时 <ComponetB />等于 1 或 2,<ComponentC />已渲染。
  • 最后,如果我改变<ComponentA />改为“否”<ComponentB /><ComponentC />将被卸载并且它们的值将被清除。

这里的工作示例 https://codesandbox.io/s/mui-rfhv6-001-xy39c

另一方面,在 V7 当我更改 <ComponentA /> 时改为“否”,<ComponentB />已卸载,但其值未清除。因此,<ComponentC />未卸载。

此处的工作示例:https://codesandbox.io/s/mui-rhfv7-001-rpg21

我尝试过设置 shouldUnregister: true如下所示,但仍然得到相同的行为。

const { control, watch, handleSubmit } = useForm({
  mode: "all",
  shouldUnregister: true
});

我错过了什么?

最佳答案

这是对版本 7 的重大更改。来自 migration guide :

Important: input value and reference will no longer get removed after unmount.

解决方案是检测何时应卸载组件并调用 unregister() 手动清除该字段:

const { ...props, unregister } = useForm();

useEffect(() => {
  if (watchRadio !== "Yes") {
    unregister("numOfSup");
  }
}, [watchRadio, unregister]);

您可以查看主题here的问题。搜索shouldUnregister以查看相关信息。

现场演示

Edit 67327916/react-hook-form-v7-key-value-in-fromstate-not-cleared-after-unmounting-its-regi

关于reactjs - react 钩子(Hook)形式 V7 : value is not cleared after unmounting its registered component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67327916/

相关文章:

javascript - 如何使react-hook-form在一页中使用多个表单?

javascript - React Hook 表单 Controller 问题

reactjs - React 中的 Angular 服务

javascript - “状态”未定义 no-undef

Material-ui,没有这样的文件或目录,打开 '.\node_modules\@babel\package.json'

javascript - Material UI - MultiSelect Popup Anchor 在选择上移动

javascript - 在 JavaScript 中初始化对象中的空数组

javascript - 功能性无状态组件中的 PropTypes

javascript - 将变量传递到自定义按钮

material-ui - React-Testing-Library 找不到具有给定角色和名称的组件