使用备用路由配置的 React Router 重定向

React Router redirect using alternate route configuration

我想使用 React Router 的备用配置:https://github.com/rackt/react-router/blob/1.0.x/docs/guides/basics/RouteConfiguration.md#alternate-configuration

但是,我无法使重定向正常工作。我试过这个:

const routes = {
  childRoutes: [
    { path: '/test', component: Test },
  ],
  component: App,
  path: '/',
  redirect: {
    from: '/',
    to: '/test',
  },
};

据我所知,没有这方面的文档。该功能是否存在?应该怎么做?

将您发布的 link 中的示例代码与上面的示例(在 Preserving URLs 中)进行比较,我认为这两个示例都指的是设置相同的路由(唯一的区别可能是最后一个使用 备用配置)。并且我们可以推断,当前进行重定向的方式是使用 onEnter 函数。

例如,如果你想要这个(使用 JSX):

<Redirect from="messages/:id" to="/messages/:id" />

并且你使用备用配置,你必须这样写:

{ path: 'messages/:id',
  onEnter: function (nextState, replaceState) {
    replaceState(null, '/messages/' + nextState.params.id)
  }
}

更新:您的具体情况很特殊,因为您想从 / 重定向,所以您可能想尝试使用 IndexRedirect or indexroute.