React Router:将所有路由作为数组获取 [英] React Router: get all routes as array

查看:57
本文介绍了React Router:将所有路由作为数组获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有现有的库可以将我的路由实例减少为一组路径?

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

示例:

    <Route path="/" component={App}>
      <Route path="author" component={Author}>
        <Route path="about" component={About}/>
      </Route>
      <Route path="users" component={Users} />
    </Route>

输出

['/', '/author', '/author/about', '/users']

我可以编写一个只有几行代码的reduce函数来解决这个问题,但我想知道是否有一个现有的库可以为我做到这一点并处理使用反应路由器表示路由的不同方式.

I could write a reduce function that will have few lines of code and solve that, but I was wondering if there is an existing library that will do that for me and take care of the different ways of representating routes using react router.

推荐答案

由于我没有找到任何东西,我最终为此创建了一个库...

As I did not find anything, I ended up creating a library for that...

https://github.com/alansouzati/react-router-to-array

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import reactRouterToArray from 'react-router-to-array';
// or var reactRouterToArray = require('react-router-to-array');

console.log(reactRouterToArray(
  <Route path="/" component={FakeComponent}>
    {/* just to test comments */}
    <IndexRoute component={FakeComponent} />
    <Route path="about" component={FakeComponent}>
      <Route path="home" component={FakeComponent} />
      <Route path="/home/:userId" component={FakeComponent} />
    </Route>
    <Route path="users" component={FakeComponent} />
    <Route path="*" component={FakeComponent} />
  </Route>)
); //outputs: ['/', '/about', '/about/home', '/users']

这篇关于React Router:将所有路由作为数组获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆