axios 如何在react中使用对象内部的if条件

aydmsdu9  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(145)

我试图将一些数据作为有效负载传递给api,我很难将条件放入对象中。我有一个名为payload的对象,我想通过检查名为profession的状态值将其传递给api。

const payload ={
  name: registerData.fullname,
  password: registerData.password,
  confirm_password: registerData.confirmPassword,
  email: registerData.email,
  additional_info: {
    profession == "Student" ? (
    universityname: values.universityname,
    course: values.course,
    start_year: values.start_year,
    end_year: values.end_year, ) : 
   (professorUniversity: values.professorUniversity,
    department: values.department,
    organizationName: values.organizationName,
    organizationLocation: values.organizationLocation,
    investorCompany: values.investorCompany,
    investorCompanyWebsite: values.investorCompanyWebsite,
    companyName: values.companyName,
    govtSector: values.govtSector,
    govtDesignation: values.govtDesignation,
    )
  }, 
};
  // I'm passing the payload in the api.
 api.post("some-url/register", payload);

正如你在上面看到的,如果条件为真,我想传递整个键和值。如果profession不是student,我甚至不传递universityname键。

mzillmmw

mzillmmw1#

您应该使用ternaryspread operator的组合

const payload ={
  name: registerData.fullname,
  password: registerData.password,
  confirm_password: registerData.confirmPassword,
  email: registerData.email,
  additional_info: {
    ...(profession == "Student" ? {
    universityname: values.universityname,
    course: values.course,
    start_year: values.start_year,
    end_year: values.end_year, } : 
    {professorUniversity: values.professorUniversity,
    department: values.department,
    organizationName: values.organizationName,
    organizationLocation: values.organizationLocation,
    investorCompany: values.investorCompany,
    investorCompanyWebsite: values.investorCompanyWebsite,
    companyName: values.companyName,
    govtSector: values.govtSector,
    govtDesignation: values.govtDesignation,
    })
  }, 
};

我已经解释了类似于here的内容
举个例子:

let car = "BMW";

const result = {

  ...(car === "BMW" ? {
    make: "Germany"
  } : {
    make: "other"
  })

};

console.log(result);

相关问题