代码之家  ›  专栏  ›  技术社区  ›  Sooraj

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

  •  0
  • Sooraj  · 技术社区  · 6 年前

    我正在尝试在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 回复  |  直到 6 年前
        1
  •  1
  •   Shubham Khatri    6 年前

    您应该编写一个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>
    

    您不想验证的任何路由都将被记为普通路由。