简体   繁体   English

反应钩子表单方法 - setValue - 不起作用

[英]React hook form method - setValue - doesn't work

I have some clearable select, and I want to reset the applets field in state to an empty array.我有一些可清除的选择,我想将状态中的applets字段重置为空数组。

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>
  );
};

the problem is that clearing the selection on UI with setValue("applets", []);问题是使用setValue("applets", []);清除 UI 上的选择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由于某种原因不工作,我不明白为什么,以及如何在没有reset方法的情况下做到这一点,重置整个状态,而不仅仅是我理解的单个属性

You should always register fields if you want to use them as RHF's form state.如果要将字段用作 RHF 的表单状态,则应始终注册字段。

  React.useEffect(() => {
    register("applets");
  }, [register]);

This fixes an issue.这解决了一个问题。

Just to follow up on this, it is indeed the right solution provided by AuthorProxy.只是为了跟进,这确实是 AuthorProxy 提供的正确解决方案。

Using defaultValues doesn't register the fields (it seems that they are still added to the formData on submit, but since they are not registered, any user triggered changes to these fields won't reflect on the formData).使用 defaultValues 不会注册这些字段(似乎它们仍然在提交时添加到 formData 中,但是由于它们没有注册,任何用户触发的对这些字段的更改都不会反映在 formData 上)。

You have to register every field you want the user to be able to interact with.您必须注册您希望用户能够与之交互的每个字段。 We usually register fields via inputs in the JSX, but we also need to register the array since there is no input for it in the JSX.我们通常通过 JSX 中的输入来注册字段,但我们也需要注册数组,因为在 JSX 中没有它的输入。

As per shown by the author of the react hook form library.如反应钩子表单库的作者所示。

https://github.com/react-hook-form/react-hook-form/discussions/3160 https://github.com/react-hook-form/react-hook-form/discussions/3160

And sandbox和沙盒

https://codesandbox.io/s/inspiring-wood-4z0n0?file=/src/App.tsx https://codesandbox.io/s/inspiring-wood-4z0n0?file=/src/App.tsx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM