我正在使用帶有不以 else 結尾的 if 陳述句的 map 函式。我必須嚴格只顯示定義的 recourseTypes。
在 eslint 中,我的 => 出現錯誤,因為它沒有以 else 結尾
Array.prototype.map() 期望在箭頭函式結束時回傳一個值。
有沒有正確的方法來寫這個?
代碼:
routes: async () => {
const apiURL = process.env.BASE_URL
const response = await axios.get(`${apiURL}/urls`)
const { data: resources } = response.data
const urlModule = resources.map((resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
}
} else if (resourceType === 'product') {
return {
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
}
} else if (resourceType === 'category') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.7,
}
} else if (resourceType === 'document') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
}
}
})
return [
{
url: '/',
changefreq: 'daily',
priority: 1,
},
{
url: '/account',
changefreq: 'daily',
priority: 1,
},
{
url: '/account/order-history',
changefreq: 'daily',
priority: 1,
},
...urlModule,
]
},
uj5u.com熱心網友回復:
澄清: resources陣列包含我們使用if/else子句比較的所有資源型別?AsArray.map()將回傳與輸入陣列包含相同數量的元素,否則它將回傳未定義。
建議:if/else-if我們可以使用多條代替多if陳述句以獲得更好的性能。
演示:
// Response coming from API.
const resources = [{
resourceType: 'brand',
url: 'brandUrl'
}, {
resourceType: 'product',
url: 'productUrl'
}, {
resourceType: 'category',
url: 'categoryUrl'
}, {
resourceType: 'document',
url: 'documentUrl'
}];
// Array of required ResourceTypes.
const requiredResourceTypes = ['brand', 'product', 'document'];
// Logic to filter and get the URL's object of the required resourceTypes.
const urlModule = resources.filter(({resourceType}) => requiredResourceTypes.includes(resourceType)).map((resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
}
}
if (resourceType === 'product') {
return {
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
}
}
if (resourceType === 'category') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.7,
}
}
if (resourceType === 'document') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
}
}
});
console.log(urlModule);
性能測驗結果截圖:

uj5u.com熱心網友回復:
你需要找出一個默認回傳的else情況。從技術上講,它不需要在一個else塊中,因為您在其他if塊中回傳,它可以只是在函式的末尾。為了確保只包含 allowed resourceTypes,您可以回傳某種輸出,如果有人沒有使用 right ,您可以將其識別為“錯誤” resourceType。你說你不想 return null,大概是因為你不希望它出現在最終的陣列中,所以你可以 returnnull然后用一個簡單的過濾器.filter(item => item)來確保一切都是真實的,或者你可以明確地檢查null. 無論哪種方式,您都必須回傳某種可識別的“錯誤”默認值并處理這種情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/493591.html
下一篇:如何有條件地為道具添加值?
