Fin*_*ary 8 typescript reactjs mongoose-schema react-hook-form
我正在使用 useFieldArray 从后端 api 获取默认值。我的类别是一个字符串数组。但是,react-hook-form 仅支持对象数组。这是我的猫鼬的架构
type BookDocument = Document & {
title: string
description: string
categories: string[]
language: string
publicationYear: number
}
const bookSchema = new Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
categories: [{ type: String, requried: true }],
language: { type: String, required: true },
publicationYear: { type: Number, required: true },
},
{ timestamps: true }
)
Run Code Online (Sandbox Code Playgroud)
因此,我必须从前端修改我的表单,如下所示:
type FormData = {
title: string
description: string
categories: { category: string }[]
language: string
year: number
}
const {
handleSubmit,
control,
formState: { errors },
} = useForm<FormData>({
mode: 'onBlur',
defaultValues: {
title: book.title ?? '',
description: book.description ?? '',
categories:
book.categories.map((elem) => {
return { category: elem }
}) ?? '',
language: book.language ?? '',
year: book.publicationYear ?? '',
},
})
Run Code Online (Sandbox Code Playgroud)
您可以调用handleSubmit
已解构为 const 的函数(位于control
代码片段上方)。您可以选择在何处调用它handleSubmit
- 可能在表单上的按钮上 - 并且handleSubmit
您可以调用回调,而不是仅仅调用 ,如下所示:
const handleFormSubmission = (data: any) => {
handleSubmit(wrappedSubmit)(data);
Run Code Online (Sandbox Code Playgroud)
};
归档时间: |
|
查看次数: |
10593 次 |
最近记录: |