如何从ReactRouter获取所有已定义的路由?

时间:2016-11-21 17:39:43

标签: javascript reactjs react-router

我定义了这样的路线:

window.myRoutes = ReactDOM.render((
    <ReactRouter.Router history={ReactRouter.browserHistory}>

        <ReactRouter.Route  path="/" component={Home}>
            <ReactRouter.IndexRoute
                component={Main}
            />
            <ReactRouter.Route
                    path="/subpath"
                    component={SubPath}
            />
            <ReactRouter.Route
                    path="/subpath2"
                    component={SubPath2}
            />
        </ReactRouter.Route>
    </ReactRouter.Router>
), document.getElementById( "main" ) );

但是当我尝试在另一个组件的componentDidMount()中访问它时,它是未定义的:

componentDidMount() { console.log( window.myRoutes ); }

如何定义所有路线?

注意:我不仅仅想要this.props.routes中的路线,因为它只是通往当前路线的所有路线

1 个答案:

答案 0 :(得分:0)

使用React Router v2 / 3,<Route>组件实际上不会渲染任何内容。它们只是转换为<Router>用来匹配当前位置的路径名的对象。如果你想拥有一个包含所有路径的对象,就很容易将它们定义为一个对象。

<Router history={browserHistory}>
  <Route  path="/" component={Home}>
    <IndexRoute component={Main} />
    <Route path="/subpath" component={SubPath} />
    <Route path="/subpath2" component={SubPath2} />
  </Route>
</Router>

相当于

var routes = {
  path: '/',
  component: Home,
  indexRoute: {component: Main}
  childRoutes: [
    {
      path: 'subpath',
      component: Subpath
    },
    {
      path: 'subpath2',
      component: Subpath2
    }
  ]
}
<Router history={browserHistory} routes={routes} />