簡體   English   中英

使用 ES6 Maps for react-router,我們如何調整 Map.get?

[英]Using ES6 Maps for react-router, how can we tweak Map.get?

我用new Map()創建了一個地圖來在我的應用程序中存儲我的 RR4 配置。

當我得到/countries/1時,我想訪問/countries/:id的值

routesMap.get('/countries/1') 
// should return the same as to routesMap.get('/countries/:id')

routesMap.get('/countries/1/comments/20'); 
// should match routesMap.get('/countries/:countryId/comments/:id')

通過從Map創建一個類,我如何調整 get 以使其更智能地獲取我的 react-router-dom 路徑?

一個簡單的嘗試將類似於以下內容

 class RouteMap extends Map { get(key) { let match; // exact match if (this.has(key)) return super.get(key); // not exact match, need to apply logic for (let route of this.keys()) { const reg = new RegExp(`^${route.replace(/:\\w+/g,'\\\\w+')}$`); if (!match && reg.test(key)) match = route; } return super.get(match); } } const routesMap = new RouteMap(); routesMap.set('/countries/:id', 'just id') routesMap.set('/countries/:countryId/comments/:id', 'id and country') console.log(routesMap.get('/countries/:id')); console.log(routesMap.get('/countries/1')); console.log(routesMap.get('/countries/:countryId/comments/:id')); console.log(routesMap.get('/countries/1/comments/20'));

但可能需要進一步的工作才能變得更加靈活、高效並處理諸如尾隨 / 等邊緣情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM