reactjs - 在应用程序中添加反应路线
问题描述
我在我的应用程序中实现了一些路由:
<Router>
<Switch>
<UnAuthRoute path="/login">
<Login />
</UnAuthRoute>
<RoleRoute path={"/"}>
<User />
</RoleRoute>
<RoleRoute path={"/admin"}>
<Admin />
</RoleRoute>
<Route path="*" />
</Switch>
</Router>
此路线应遵守以下条件:
If user access the application he should be redirected on route -> "/user"
If user try to access the route -> "/admin " he should be redirected on "/404"
If admin access the application he should be redirected on route -> "/admin "
If admin try to access the route -> "/user" he should be redirected on "/404"
If both users try to access "/login", and they are in application they should be redirected on their personal route
但我无法弄清楚为什么该应用程序不起作用。我试图模拟我的应用程序:
https
://codesandbox.io/s/bold-mclaren-9vsvh?file=/src/App.js:371-706如何修复代码以适应条件?
解决方案
您需要对代码进行少量更改才能满足您的要求。
- 在
RoleRoute.js
您将“未定义”与 null 进行比较(当 localStorage.getItem 返回 null 时),因此您始终被重定向到 404。正确的方法是与 null 进行比较。像这样:
const authenticated = localStorage.getItem("mytoken") !== null;
- 精确到
/
路线 - 确保通过
role
道具
您的代码的工作副本在沙箱中
路由代码片段
<div className="App">
<Router>
<Switch>
<UnAuthRoute path="/login">
<Login />
</UnAuthRoute>
<RoleRoute exact path={"/"} rolez="user">
<User />
</RoleRoute>
<RoleRoute path={"/user"} rolez="user">
<User />
</RoleRoute>
<RoleRoute path={"/admin"} rolez="admin">
<Admin />
</RoleRoute>
<Route path="*" />
</Switch>
</Router>
</div>
RoleRoute 代码片段
import { Route, Redirect } from "react-router-dom";
export const RoleRoute = ({ children, redirectTo, path, rolez }) => {
const authenticated = localStorage.getItem("mytoken") !== null;
const allowed = localStorage.getItem("role") === rolez;
if (!authenticated) return <Redirect to={redirectTo || "/login"} />;
else if (allowed) return <Route path={path}>{children}</Route>;
else return <Redirect to={redirectTo || "/404"} />;
};
推荐阅读
- sql - 选择匹配 C 条件的最后 N 行 (PostgreSQL)
- sql - 同一张表的 SQL 公共记录
- regex - 在谷歌表格中使用正则表达式将两个重复的句子分隔在同一个单元格中,没有空格
- windows - 自 2012 年以来,WinSock Registered IO 性能是否有所下降?
- python - ModuleNotFoundError:没有名为“x”的模块,因为找不到模块文件夹,PyInstaller
- ios - React-native 无法打开 ios 模拟器调试菜单
- javascript - 使用 CSS 色调效果保存图像
- excel - 使用单元格中的值作为宏中的范围
- reactjs - 使用 useEffect 时,我经常收到有关依赖项列表中缺少变量的警告。难道我做错了什么?
- ruby-on-rails - RSpec 在期望 raise_error 之前期望一些东西