React router - 重定向除一条以外的所有路由

React router - redirect all routes except one

我正在尝试在 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

如何从除一条路线以外的所有路线重定向?

与其编写用于身份验证的硬编码路由,不如编写 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>

任何您不想验证的路由都将被记录为正常路由