我在一个项目中工作,它的主页包含一个登录表单,要求用户插入电子邮件和密码,然后通过-if认证-用户导航到个人资料页面。下面是我在React中实现私有路由的代码部分:
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.getItem('user')
? <Component {...props} />
: <Redirect to={{ pathname: `${baseURL}/`, state: { from: props.location } }} />
)} />
)问题是,如果我把主页的链接,即使我已经登录,它导航到主页,并要求我再次输入电子邮件和密码。我想做一些事情,重定向到配置文件页面,如果他插入了主页的链接,而他的令牌仍然有效,没有过期。它是如何做到的?有什么帮助吗?
谢谢你的提醒。
发布于 2020-08-27 15:44:56
你还需要在你的主页上安装一个localStorage检查器。
useEffect(() => {
/*back to profile if the user attempt to go to home page even the user was currently logged-in*/
const isUserLogged = localStorage.getItem('user');
if (isUserLogged) {
return props.history.push(`/profile`);
}
}, []);https://stackoverflow.com/questions/63610382
复制相似问题