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



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

您不想进行身份验证的任何路由都将被写为普通路由

最新更新