反应路由器-重定向除一个路由器之外的所有路由

时间:2018-10-03 06:04:15

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

我正在尝试在React中实现受保护的路由。 以下是我的实现

if (isAuth()) {
      routesToRender = (
        <React.Fragment>
          {/* <Redirect exact from="/" to="/dashboard" /> */}
          <Route path="/" exact component={props => <Dashboard {...props} />} />
          <Route path="/dashboard" exact component={props => <Dashboard {...props} />} />
          <Route path="/settings/" exact component={props => <Settings {...props} />} />
        </React.Fragment>
      )
    } else {
      routesToRender = (
        <React.Fragment>
          <Route path="/signup/" exact component={props => <Signup {...props} />} />
          <Route path="/" exact component={props => <Login {...props} />} />
          <Redirect from="*" to="/" />
        </React.Fragment>
      )
    }

如果未通过身份验证,我想将所有路由重定向到根URL,即*,为此我使用<Redirect from="*" to="/" />。但我也希望能够访问/signup

如何从除一条之外的所有路由重定向?

1 个答案:

答案 0 :(得分:1)

您应该编写AuthRoute HOC,而不是编写用于身份验证的硬编码路由,

const AuthRoute = ({component: Component, ...rest}) => {
    if(isAuth) {
        return <Route {...rest} component={Component} />
    }
    return <Redirect to="/" />
}

并像使用它

<React.Fragment>
      {/* <Redirect exact from="/" to="/dashboard" /> */}
      <AuthRoute path="/" exact component={props => <Dashboard {...props} />} />
      <AuthRoute path="/dashboard" exact component={props => <Dashboard {...props} />} />
      <AuthRoute path="/settings/" exact component={props => <Settings {...props} />} />
 </React.Fragment>

任何您不想进行身份验证的路线都将被记录为普通路线

相关问题