React Router: get all routes as array

后端 未结 3 1333
无人及你
无人及你 2021-01-04 03:36

Is there an existing library that will reduce my route instance to an array of paths?

Example:

    

        
3条回答
  •  暖寄归人
    2021-01-04 03:50

    I recently released a library specifically for this purpose: https://github.com/elliottsj/react-router-query

    It can handle asynchronous routes (i.e. getChildRoutes / getIndexRoute), and provides not just an array of paths, but an array of "FlatRoute" objects which contain the path (fullPath), plus all of the original properties of each route, and an array of "parent" routes:

    import { query } from 'react-router-query';
    
    const routes = (
      
        
          
        
        
      
    );
    
    query('/', routes, (error, result) => {
      expect(result).toEqual([
        {
          fullPath: '/author/about'
          component: About,
          parents: [
            { path: '/', component: App },
            { path: 'author', component: Author },
          ],
        },
        {
          fullPath: '/users'
          component: Users,
          parents: [
            { path: '/', component: App },
          ],
        },
      ]);
    });
    

    Note that only "leaf" routes are included in the result: there is no "FlatRoute" object for fullPath: '/' nor fullPath: '/author'. This is to prevent including routes that are only used as a layout for child routes, e.g.

    
      
        
        
        
      
    
    

    If you want a FlatRoute for /posts, simply include an IndexRoute:

    
      
        
        
        
        
      
    
    

提交回复
热议问题