这是一个私有路由,只允许经过身份验证的用户导航到仪表板"/"
用户仍然可以返回"/login"认证成功后,如何使用私有路由防止这种情况?
import React from 'react'
import { Redirect, Route } from 'react-router'
import { useAuth } from '../contexts/AuthContext'
export default function PrivateRoute({component: Component, ...rest}) {
const{ currentUser } = useAuth()
return (
<Route
{...rest}
render={props =>{
return currentUser? <Component {...props} /> : <Redirect to ="/login" />
}}>
</Route>
)
}
您可以将登录状态保存为全局状态,然后您将为呈现登录路由设置一个条件,
const globalLoginState = true // -> you are logged in
<BrowserRouter>
<Router>
{ globalLoginState ? (
<Route exact path"/" component={DummyPageComponent} />
) : <Route path="signIn" component={DummySignInComponent} />
}
</Router>
</BrowserRouter>
我想这对你会有用的