I have created a map with new Map()
to store my RR4 configuration in my app.
I want to access the values of /countries/:id
, when I get /countries/1
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')
By creating a class from Map
, how can I tweak the get so it become more intelligent to get my react-router-dom path ?
A simple attempt would be something like the following
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'));
But might need further work to become more flexible, performant and handle edge cases like trailing / etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.