代码之家  ›  专栏  ›  技术社区  ›  Dimitri Kopriwa

将ES6映射用于react路由器,我们如何调整地图。得到吗?

  •  0
  • Dimitri Kopriwa  · 技术社区  · 7 年前

    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

    0 回复  |  直到 7 年前
        1
  •  1
  •   Gabriele Petrioli    7 年前

    简单的尝试如下

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