我有很多想要从 API 填充的字段。我如何
preprocess
它们,如果它是null
或undefined
,只需将它们转换为字符串?
我的问题是,如果它是
"null"
,我下面的代码输出为
null
代码
const formSchema = z.object({
contact: z.object({
first_name: z.string().min(1, { message: "Enter first name" }),
last_name: z.string().min(1, { message: "Enter last name" }),
title: z.preprocess((val) => String(val), z.string()),
}),
organization: z.object({
name: z.string().min(1, { message: "Enter organization name" }),
}),
});
const form = useForm<FormData>({
mode: "onTouched",
resolver,
defaultValues: {
contact: { ...recipient.contact },
organization: { ...recipient.organization },
},
});
<FormField
control={form.control}
name="contact.title"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<Input placeholder="Enter title" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
我想你所需要的只是Nullish Coalescing Operator
// ...
title: z.preprocess((val) => String(val ?? ""), z.string()),
// ...