![](/img/trans.png)
[英]Array.prototype.map() expects a value to be returned at the end of arrow function
[英]Array.prototype.map() expects a value to be returned, but can't return null as per other questions, at the end of arrow function
我正在使用帶有不以 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,
]
},
您需要找出在else
情況下返回的默認值。 從技術上講,它不需要在else
塊中,因為您在另一個if
塊中返回,它可以只是在函數的末尾。 為確保僅包含允許的resourceType
,您可以返回某種輸出,如果有人沒有使用正確的resourceType
,您將能夠將其識別為“錯誤”。 您說您不想返回null
,大概是因為您不希望在最終數組中使用它,因此您可以返回null
然后使用簡單的.filter(item => item)
進行過濾以確保一切都是真實的,或者您可以顯式檢查null
。 無論哪種方式,您都必須返回某種可識別的“錯誤”默認值並處理這種情況。
澄清: resources
數組包含我們使用if/else
子句比較的所有資源類型? 由於Array.map()
將返回與輸入數組包含的相同數量的元素,否則它將返回未定義的元素。
建議:我們可以使用多個if
語句來代替多個if/else-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);
性能測試結果截圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.