【问题标题】:React Router redirect using alternate route configuration使用备用路由配置的 React Router 重定向
【发布时间】:2016-03-28 03:10:41
【问题描述】:

我想使用 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',
  },
};

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

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

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

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

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

    而你使用Alternate Configuration,你必须这样写:

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

    更新:你的特殊情况很特殊,因为你想从/重定向,所以你可能想尝试使用IndexRedirectindexroute

    【讨论】:

    • 感谢@Protron。这并不完全有效,但使用onEnter 让我思考。这是我解决它的方法:onEnter: (nextState, transition) =&gt; { if (nextState.location.pathname === '/') { transition.to('/test', null); } },
    • @Chris 不错!但是,如果您有兴趣寻找其他解决方案,您可能需要查看我的答案中的更新。
    • transition 不是我进入函数的参数之一。我在尝试将 / 重定向到其他东西以及其他一些东西时遇到了同样的问题。这比 复杂得多,但是你可以这样做 require.ensure :/.
    猜你喜欢
    • 1970-01-01
    • 2022-12-30
    • 2021-07-24
    • 2016-04-16
    • 1970-01-01
    • 2015-09-30
    • 2020-10-08
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多