通过react-hook-form使用嵌套对象

问题描述 投票:0回答:1

我正在尝试使用react-hook-form将数据发送到我的后端,这是FormData接口:

interface FormData {
  title: string;
  // other things
  location: {
    country: string | null;
    city: string | null;
    address: string | null;
  };
}

问题是,当我提交表单并在后端(django)中观察它时,它是这样的:

<QueryDict: {'title': ['CCC'], 'location': ['[object Object]']}>

这样后端就不会为对象设置位置


编辑: 这里有 FormData 的控制台日志:

{
    "title": "test",
    "location": {
        "country": "Italy",
        "city": "Milan",
        "address": "Via xx sttembre"
    }
}

这也是

onSubmit()
功能:

const onSubmit = (data: FieldValues) => {
    const apiClient = new APIClient<FieldValues>("events/");

    apiClient
      .create(formData, { headers: { "Content-Type": "multipart/form-data" } })
      .then((res) => {
        setSuccess(true);
        return res.data;
      })
      .catch((err) => setError(err));
    console.log(data);
  };
reactjs django django-rest-framework react-hook-form
1个回答
0
投票

问题似乎是由我如何构造

FormData
对象引起的。当我将嵌套对象位置直接附加到
FormData
时,它会将其转换为字符串
'[object Object]'
,这不是我想要的。

相反,我需要单独处理嵌套对象。以下是我如何调整

onSubmit()
函数以正确处理嵌套对象:

const onSubmit = (data: FieldValues) => {
  const formData = new FormData();
  for (const key in data) {
    if (typeof data[key] === "object" && data[key] !== null) {
      // Handle nested object
      for (const nestedKey in data[key]) {
        const nestedValue = data[key][nestedKey];
        formData.append(`${key}.${nestedKey}`, nestedValue);
      }
    } else {
      formData.append(key, data[key]);
    }
  }

  const apiClient = new APIClient<FieldValues>("events/");

  apiClient
    .create(formData, { headers: { "Content-Type": "multipart/form-data" } })
    .then((res) => {
      return res.data;
    })
};
© www.soinside.com 2019 - 2024. All rights reserved.