React hook form method - setValue - doesn#39;t work(反应钩子形式方法 - setValue - 不起作用)
问题描述
我有一些可清除的选择,我想将状态中的 applet
字段重置为空数组.
I have some clearable select, and I want to reset the applets
field in state to an empty array.
const defaultFormValues = { device: { ...initialDevice }, applets: [] };
const { control, getValues, setValue, reset, handleSubmit } = useForm<CreateDeviceFormData>({
mode: "all",
reValidateMode: "onChange",
defaultValues: defaultFormValues,
resolver: yupResolver(validationSchema),
});
const onChangeHandler = React.useCallback(
(value: Experience | null) => {
if (value) {
setValue("applets", getApplets(value));
} else {
setValue("applets", []);
// reset(defaultFormValues);
}
setValue("device.experience_id", value ? value.id : undefined);
},
[templateSelector, setValue],
);
console.log("current data", getValues(), control);
return (
<>
<SomeAutocompleteComponent control={control} onChange={onChangeHandler} />
<SelectAppletsComponent control={control} />
</>
);
export const SelectAppletsComponent = ({ control, onChange }) => {
const applets = useWatch({ control, name: "applets" }) as Applet[];
const device = useWatch({ control, name: "device" }) as Device;
if (!applets.length) {
return null;
}
return (
<SpanWrapper className="p-col-8">
{applets.map((applet) => (
<LabelRadio
key={applet.id}
inputId={applet.applet_type}
value={applet.applet_type}
label={applet.name}
checked={device.applet_type === applet.applet_type}
onChange={onChange}
/>
))}
</SpanWrapper>
);
};
问题是使用 setValue("applets", []);
清除 UI 上的选择由于某种原因无法正常工作,我不明白为什么以及如何做到这一点没有 reset
方法,它会重置整个状态,而不仅仅是我理解的单个属性
the problem is that clearing the selection on UI with setValue("applets", []);
not working for some reason, and I don't understand why, and how to do it without reset
method, which resets the whole state, not just single property as I understand
推荐答案
如果要将字段用作 RHF 的表单状态,则应始终注册它们.
You should always register fields if you want to use them as RHF's form state.
React.useEffect(() => {
register("applets");
}, [register]);
这解决了一个问题.
这篇关于反应钩子形式方法 - setValue - 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:反应钩子形式方法 - setValue - 不起作用
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01