使用ES6 Maps作为React-Router,我们如何调整Map.get?

时间:2019-02-24 04:10:07

标签: javascript reactjs ecmascript-6 maps react-router-dom

我已经用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路径?

1 个答案:

答案 0 :(得分: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'));

但是可能需要做进一步的工作才能变得更加灵活,高效并处理诸如尾随等问题。