react-hook-form 问题:为什么 getValues 不返回最新值?

问题描述 投票:0回答:1

我有单选按钮:A、B 和 C。

在按钮 B 下,有一个选择框,我想仅在选择 B 时才将此选择框设置为“必需”。

这是简化的代码:

interface ButtonFormType {
    notificationType: "A" | "B" | "C";
    selectedId?: string;
}
const {
        register,
        handleSubmit,
        getValues,
        watch,
        formState: { errors },
    } = useForm<ButtonFormType>();

.
.
.

return(
 <form onSubmit={submit}>
  <RadioGroup defaultValue={getValues("buttonType")}>
    <VStack>
      <Radio {...register("buttonType")} value={"A"}> Button A </Radio>
      <Radio {...register("buttonType")} value={"B"}> Button B </Radio>
      <FormControl isInvalid={!!errors[`selectedId`]}>
         <Select
            placeholder={"select"}
            {...register("selectedId", {
                required:
                   getValues("buttonType") === "B"
                   ? "please select id"
                   : false,
            })}
         >
            {idList.map(({ id, title }) => {
               return (
                  <option key={id} value={id}>
                       {title}
                  </option>
                                        );
            })}
         </Select>
      </FormControl>
     <Radio {...register("buttonType")} value={"C"}> Button C </Radio>
    </VStack>
   </RadioGroup>
                  
   <HStack marginY="40px" spacing={4}>
      <Button type="submit"> Submit </Button>
   </HStack>
</form>
)

当我选择按钮 B(不从选择框中选择任何内容)并点击提交按钮时, 它不会给我任何错误。

如果我再次点击提交按钮,则会出现错误消息。

我检查发现,当我更改buttonType时,

getValues("buttonType")
并没有更新。

点击提交按钮后就会更新。为什么?

我可以通过将

getValues
更改为
watch
来解决这个问题

required:
                   watch("buttonType") === "B"
                   ? "please select id"
                   : false,

但仍然不明白为什么 getValues 不起作用。 有谁知道吗

reactjs next.js react-hook-form chakra-ui
1个回答
0
投票

您可以参考此说明。

watch 和 getValues 的区别在于 getValues 不会触发重新渲染或订阅输入更改。

所以

getValues
不知道你的实时变化,但
watch
知道。

© www.soinside.com 2019 - 2024. All rights reserved.