简体   繁体   English

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

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

I have created a map with new Map() to store my RR4 configuration in my app.我用new Map()创建了一个地图来在我的应用程序中存储我的 RR4 配置。

I want to access the values of /countries/:id , when I get /countries/1当我得到/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')

By creating a class from Map , how can I tweak the get so it become more intelligent to get my react-router-dom path ?通过从Map创建一个类,我如何调整 get 以使其更智能地获取我的 react-router-dom 路径?

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.但可能需要进一步的工作才能变得更加灵活、高效并处理诸如尾随 / 等边缘情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM