javascript - ReactJS -> 我如何制作受限路线?
问题描述
我有几个如下所示的反应路线:
<Route exact path='/Home' component={Products}/>
<Route path='/Login' component={Login}/>
<Route path='/Register' component={Register}/>
<Route path='/ProfilePage' component={ProfilePage}/>
而且我想做到这一点,以便profilepage
只有已登录的用户才能访问该路线,但我几乎不知道这将如何发生。我考虑过创建一个状态,loginStatus
直到 cookieloginStatus
过期(例如一周左右),然后以某种方式如果loginStatus='logged'
路由器profilepage
可以访问,否则它将重定向到显示错误的某个页面,使用另一条路线。我不知道该怎么做。
解决方案
Try create a custom route component with login condicional and Redirect: Example:
function PrivateRoute({ children, ...rest }) {
return (
<Route
{...rest}
render={({ location }) => {
return isAuthenticated === true ? (
children
) : (
<Redirect
to={{
pathname: "/Login",
state: { from: location },
}}
/>
);
}}
/>
);
}
推荐阅读
- mysql - 如何解决 Java EE 项目中的时区错误?
- ios - pod install 给我错误
- python - 通过 Python 中的方法进行字符串操作
- reactjs - 带有反应钩子的倒数计时器
- javascript - JavaScript:加速我的脚本。最佳实践?
- vim - 为 Gvim 中的每个缓冲区设置不同的配色方案
- node.js - 如何在 MongoDb 中启动事务?
- reactjs - CkEditor5 禁用内容过滤 (ReactJs)
- vba - 关闭所有打开的模块的宏
- openmp - 英特尔 OpenMP 库通过设置 KMP_AFFINITY=scatter 显着降低 AMD 平台上的内存带宽