反应钩子形式方法 - 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]);
这解决了一个问题.
相关文章