如何动态添加重定向到 react-router?

How do I add redirect to react-router dynamically?

我有登录组件,未经身份验证的用户应该可以使用该组件。并且在身份验证之后该组件应该不可用。

   var routes = (
      <Route handler={App}>
        <Route name="signIn" handler={signIn}/>
        {/* redirect, if user is already authenticated */}
        { localStorage.userToken ? (
            <Redirect from="signIn" to="/user"/>
          ) : null
        }
      </Route>
    );

Router.run(routes, (Handler, state) => {
  React.render(<Handler {...state}/>, document.getElementById('main'));
});

如果用户在身份验证后出于任何原因重新加载了 web 应用程序,此代码将完美运行,但如果用户未重新加载 web 应用程序,则当然不会。 我尝试对 SignUp 组件使用 this.context.router.transitionTo,但效果很糟糕 - 组件被渲染,然后这个脚本被执行。

所以我想将重定向添加到 routes 变量中,使路由器重定向,甚至无需尝试呈现组件。

我推荐另一种方法,而不是检查您的身份验证流程和有条件地呈现特定路由:

如果您使用的是 react-router 0.13.x,我建议您使用 willTransitionTo methods on your components when you need to check authentication. It is called when a handler is about to render, giving you the opportunity to abort or redirect the transition (in this case, check if user is authenticated, redirect to another path if not). See auth-flow example here: https://github.com/ReactTraining/react-router/blob/v0.13.6/examples/auth-flow/app.js

对于 >0.13.x 的版本,它将是 onEnter and Enterhooks. See the auth-flow example here: https://github.com/rackt/react-router/blob/master/examples/auth-flow/app.js

基本上,您将身份验证检查流程从您的 routes 变量移开,并进入转换 events/hooks。在实际呈现路由处理程序之前,检查身份验证,并将用户重定向到另一条路由。