我正在使用 React 和 nextJS 做 web 開發人員,我想在我的網頁上呈現一個串列,串列資訊來自服務器(我使用 axios get 函式獲取資訊)。然而,一些 JSON 物件缺少名稱、地址等資訊。我的解決方案是使用 If-else 來處理不同型別的 JSON 物件。這是我的代碼:
getPatientList(currentPage).then((res: any) => {
console.log("Response in ini: " , res);
//console.log(res[0].resource.name[0].given[0]);
const data: any = [];
res.map((patient: any) => {
if ("name" in patient.resource) {
let info = {
id: patient.resource.id,
//name:"test",
name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
} else {
let info = {
id: patient.resource.id,
name: "Unknow",
//name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
}
});
有沒有更聰明的有效方法來解決這個問題?我是 TS 和 React 的新手
uj5u.com熱心網友回復:
改為使用條件運算子在可能的名稱之間交替。您還應該直接從.map回呼中回傳,而不是推送到外部變數。
getPatientList(currentPage).then((res) => {
const mapped = res.map(({ resource }) => ({
id: resource.id,
// want to correct the spelling below?
name: "name" in resource ? resource.name[0].given[0] : "Unknow",
birthDate: resource.birthDate,
gender: resource.gender,
}));
// do other stuff with mapped
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/522027.html
標籤:javascript反应
上一篇:警報無限次出現且無法關閉
