reactjs React钩形:useForm未在formState中返回任何错误

wqsoz72f  于 2023-03-22  发布在  React
关注(0)|答案(1)|浏览(92)

我正在使用T3堆栈+ react-hook-form + zodResolver:@hookform/resolvers/zod创建应用程序
我定义了一个zod模式,如下所示

export const AccountSchema = z.object({
  id: z.string().uuid().optional(),
  title: z.string().min(1, { message: 'Title is required' }),
  description: z.string().min(1, { message: 'Description is required' }),
});

export type Account = z.infer<typeof AccountSchema>;

在一个组件中,我使用了useFormHook,如下所示

const editForm = useForm<Account>({ resolver: async (val, ctx, opt) => {
    const res = await zodResolver(AccountSchema)(val, ctx, opt);
    console.log('Validation Result: ', res, val);
    return zodResolver(AccountSchema)(val, ctx, opt);
  }});

使用的 Package :

"zod" -> "3.20.7"
"@hookform/resolvers" -> "2.9.11"
"react-hook-form" -> "7.43.5"

**问题:**查看控制台日志,我可以看到zodResolver正在将正确的错误传递给useForm resolver,但在formState中,对象错误始终是未定义的,即:editForm.formState.errors.title始终返回未定义的内容。

gstyhher

gstyhher1#

好吧,它就发生在我身上,结果是我在表单字段中调用了错误的onSubmit操作:

const schema = z.object({
  description: z.string().min(3).max(50).nonempty(),
  amount: z.number().min(0).nonnegative(),
  category: z.enum(categories),
});    

type FormData = z.infer<typeof schema>;
    
    const DataForm = () => {
      const {
        register,
        handleSubmit,
        formState: { errors },
      } = useForm<FormData>({ resolver: zodResolver(schema) });

然后,更改表单onSubmit解决了这个问题:

<form onSubmit={handleSubmit()}>

希望这能帮上忙。

相关问题