如何使用react路由器将重定向重写为普通路由?

时间:2016-07-19 13:27:56

标签: javascript react-router jsx

使用react 15.1.0react-router 2.5.2,我希望重写以下JSX语法:

<Router routes={routes} history={hashHistory}>
  <Redirect from="/" to="/users" />
  <Route path="/" component={Navigation}>
    <Route path="/users" component={UsersPage}/>
    <Route path="/endpoints" component={EndpointsPage}/>
  </Route>
</Router>

进入普通路线,如下:

const routes = {
  path: '/',
  component: Navigation,
  childRoutes: [
    {path: '/users', component: UsersPage},
    {path: '/endpoints', component: EndpointsPage}
  ],
  onEnter: (nextState, replace) => replace('/users')
};

React.render(<Router routes={routes} history={hashHistory}/>, element);

然而,后者的结果始终是:

  

未捕获RangeError:超出最大调用堆栈大小

onEnter: (nextState, replace) => replace('/users')显然不足以取代<Redirect from="/" to="/users" />。如何成功重写重定向?是否有更好的方法可以导航/始终以/users结束?

1 个答案:

答案 0 :(得分:3)

我不知道有一个名为IndexRedirect的东西。使用索引重定向,在普通路由中执行此操作的正确方法是:

const routes = {
  path: '/',
  component: Navigation,
  indexRoute: {onEnter: (nextState, replace) => replace('/users')},
  childRoutes: [
    {path: '/users', component: UsersPage},
    {path: '/endpoints', component: EndpointsPage}
  ]
};

React.render(<Router routes={routes} history={hashHistory}/>, element);