不匹配时反应路由器v4重定向

Ego*_*gor 8 authentication routing reactjs react-router react-router-v4

我是react-router的新手(通常是客户端路由),所以我可能会想到这一切都是错误的。如果是这样的话,请提前抱歉。

基本上只想实现3条简单的规则:

  • 如果没有用户,请重定向到“ /登录”
  • 否则,如果路由不存在,请重定向到“ /”(根)
  • 否则让用户转到请求的路线

我跟踪中的用户this.state.user。我当前的路由器似乎遵循前2条规则,但是只允许经过身份验证的用户查看主页(“ / profile”重定向到“ /”),所以我知道我做错了事,但无法弄清楚。

 <Router>
    {this.state.user ? (
      <Switch>
        <Route path="/" exact component={Home}/>
        <Route path="/profile" exact component={Profile}/>
        <Route render={() => (<Redirect to="/" />)}/>
      </Switch>
    ) : (
      <Switch>
        <Route path="/login" exact component={Login}/>
        <Route render={() => (<Redirect to="/login" />)}/>
      </Switch>
    )}
 </Router>
Run Code Online (Sandbox Code Playgroud)

任何建议表示赞赏。谢谢

GG.*_*GG. 13

对于到达这里的任何人,如果没有一条路线匹配,则寻找如何重定向:

<Switch>
  // ... your routes
  <Route render={() => <Redirect to="/" />} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

请注意,路线必须是的直接子级<Switch>,例如,这不起作用:

<Switch>
  <Fragment>
    // ... your routes
    <Route render={() => <Redirect to="/" />} />
  </Fragment>
</Switch>
Run Code Online (Sandbox Code Playgroud)

(也许在最新版本的react-router中修复)

  • 这很有效,感谢您澄清直接儿童的问题。 (2认同)

小智 11

答案很简单

<Switch>
  <Route path="/login" exact component={Login}/>
  {!this.state.user && <Redirect to='/login' />}
  <Route path="/" exact component={Home}/>
  <Route path="/profile" exact component={Profile}/>
  <Redirect to="/" />
</Switch>
Run Code Online (Sandbox Code Playgroud)

交换机和路由器的主要区别在于路由器将尝试执行所有匹配的路径并将内容附加到一起,交换机将在第一次匹配时停止。

我的应用程序有类似的方法,但我将受保护的路由包装在一个单独的文件中,然后将用户配置文件包装为 HOC

export const App = () => (
  <Switch>
    <Route exact path='/login' component={Login} />
    {!hasToken() && <Redirect to='/login' />}
    <Route path='/' component={ProtectedRoute} />
  </Switch>
)
Run Code Online (Sandbox Code Playgroud)

protectedRoute.js

const ProtectedRoute = ({ userInfo }: Props) => (
  <Layout userInfo={userInfo}>
    <Switch>
      <Route exact path='/a' component={A} />
      <Route exact path='/b' component={B} />
      <Route path='/c' component={C} />
      <Redirect to='/a' />
    </Switch>
  </Layout>
)

export default withUserInfo(ProtectedRoute)
Run Code Online (Sandbox Code Playgroud)


Rya*_*yan 2

您是否考虑过使用Route包装器在需要用户时检查用户Route

const CanHasRouteAccess = ({ component: Component, iHasUser, ...rest }) => {
  return iHasUser ? (
    <Route {...rest} render={props => <Component {...props} />} />
  ) : (
    <Redirect to="/" />
  );
};
Run Code Online (Sandbox Code Playgroud)

您可以将属性传递给路由,或者在没有用户时重定向到主页。

<CanHasRouteAccess
  path="/personal-data"
  exact
  component={Profile}
  iHasUser={Boolean(user)}
  />
Run Code Online (Sandbox Code Playgroud)