将 ES6 Maps 用于 react-router,我们如何调整 Map.get?
Using ES6 Maps for react-router, how can we tweak Map.get?
我已经使用 new Map()
创建了一个地图,用于将我的 RR4 配置存储在我的应用程序中。
我想访问 /countries/:id
的值,当我得到 /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')
通过从 Map
创建一个 class,我如何调整 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'));
但可能需要进一步的工作才能变得更加灵活、高效并处理尾随等边缘情况。
我已经使用 new Map()
创建了一个地图,用于将我的 RR4 配置存储在我的应用程序中。
我想访问 /countries/:id
的值,当我得到 /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')
通过从 Map
创建一个 class,我如何调整 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'));
但可能需要进一步的工作才能变得更加灵活、高效并处理尾随等边缘情况。