不匹配时React router v4重定向

时间:2018-05-15 01:33:23

标签: reactjs authentication routing react-router react-router-v4

我是反应路由器(以及一般的客户端路由)的新手,所以我可能会想到这一切都错了。如果是这样的话,请提前抱歉......

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

  • 如果没有用户,请重定向到' / login'
  • 如果路线不存在,则重定向到' /' (根)
  • 让用户转到请求的路线

我在this.state.user中跟踪用户。我当前的路由器似乎遵循前两个规则,但只允许经过身份验证的用户看到主页(' / 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>

任何建议表示赞赏。谢谢

3 个答案:

答案 0 :(得分:6)

对于到达此处的任何人,如果没有匹配的路线,则该如何进行重定向:

<Switch>
  // ... your routes
  <Route render={() => <Redirect to="/" />} />
</Switch>

答案 1 :(得分:2)

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

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

当没有用户时,您可以将道具传递给路线或导致重定向到主页。

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

答案 2 :(得分:1)

答案很简单

America/Detroit

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

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

<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>

protectedRoute.js

export const App = () => (
  <Switch>
    <Route exact path='/login' component={Login} />
    {!hasToken() && <Redirect to='/login' />}
    <Route path='/' component={ProtectedRoute} />
  </Switch>
)
相关问题