React-hook-form useFieldArray 用于字符串数组而不是对象

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)

问题是在调用api请求时。网络负载将如下所示,因此无法发送到后端 在此输入图像描述

Qoh*_*ech 0

您可以调用handleSubmit已解构为 const 的函数(位于control代码片段上方)。您可以选择在何处调用它handleSubmit- 可能在表单上的按钮上 - 并且handleSubmit您可以调用回调,而不是仅仅调用 ,如下所示:

const handleFormSubmission = (data: any) => {
handleSubmit(wrappedSubmit)(data);
Run Code Online (Sandbox Code Playgroud)

};