返回
如何使用 React Hook Form、Zod 和 Ant Design 获取理想的表单数据?
javascript
2024-03-09 08:04:21
React Hook Form、Zod 和 Ant Design:获取理想表单数据
问题陈述
在使用 React Hook Form、Zod 和 Ant Design 构建表单时,获取符合预期数据结构可能会遇到困难。本文将指导你解决这个问题,并提供解决特定错误的详细步骤。
解决方法
要获取理想的表单数据,请按照以下步骤进行操作:
-
验证 Zod 模式 :确保 Zod 模式与所需的数据结构完全匹配。
-
更新表单验证 :将
zodResolver
更新为最新版本的 Zod,以确保正确验证。 -
验证
InputNumberField
组件 :添加required
属性以强制填写transport_id
字段。 -
检查表单数据 :使用
watch
函数在提交之前检查表单数据,及时发现错误。 -
处理提交错误 :在
onSubmit
处理程序中,添加代码来处理提交错误并提供有用的反馈。
示例代码
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { InputNumberField, Form } from "antd";
const defaultValues = {
subject_travel: "yes",
transport_percentages: [
{ transport_id: 1, percentage: 20 },
{ transport_id: 2, percentage: 40 },
{ transport_id: 3, percentage: 40 },
],
do_you_know_avg_distance_travelled: "no",
};
const zodSchema = z.object({
subject_travel: z.enum(["yes", "no"]),
transport_percentages: z
.array(
z.object({
transport_id: z.number().nonnegative().optional(),
percentage: z.number().min(0).max(100),
})
)
.optional(),
do_you_know_avg_distance_travelled: z.enum(["yes", "no"]),
});
const TransportPercentageField = ({ id, name, ...rest }) => {
return (
<InputNumberField {...rest} id={id} name={name} required />
);
};
const App = () => {
const {
watch,
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(zodSchema, {
errorFormatter: {
path: (error) => error.path[0],
},
}),
defaultValues,
});
const onSubmit = async (data) => {
try {
const result = await zodSchema.parseAsync(data);
console.log("Validated data:", result);
} catch (error) {
console.error("Error:", error);
alert("There was an issue with your submission. Please check the errors and try again.");
}
};
return (
<Form onFinish={handleSubmit(onSubmit)}>
{/* ... Form fields */}
<button type="submit">Submit</button>
</Form>
);
};
常见问题解答
1. 为什么我的 transport_id
字段没有被验证?
确保 InputNumberField
组件具有 required
属性,并且 Zod 模式正确地将 transport_id
定义为非空值。
2. 我如何处理提交错误?
在 onSubmit
处理程序中,添加代码来记录错误并向用户显示有用信息。
3. 我如何检查表单数据是否符合预期?
使用 watch
函数在提交表单之前检查数据。
4. 如何正确更新 zodResolver
?
使用 zodResolver
的最新版本,并且将 errorFormatter
选项设置为所需的形式。
5. 我在哪里可以找到更多关于 React Hook Form、Zod 和 Ant Design 的信息?
官方文档和社区论坛是获取更多信息的宝贵资源。