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

问题描述 投票:1回答:1

我用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创建一个类,我如何调整get,这样才能更灵活地获得react-router-dom路径?

javascript reactjs ecmascript-6 maps react-router-dom
1个回答
1
投票

一个简单的尝试将是如下所示

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'));

但是可能需要进一步的工作来变得更灵活,更高效并处理诸如尾随等的边缘情况。

© www.soinside.com 2019 - 2024. All rights reserved.