在 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
以查看相关信息。
现场演示
关于reactjs - react 钩子(Hook)形式 V7 : value is not cleared after unmounting its registered component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67327916/