首页 > 解决方案 > 在应用程序中添加反应路线

问题描述

我在我的应用程序中实现了一些路由:

  <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如何修复代码以适应条件?

标签: reactjs

解决方案


您需要对代码进行少量更改才能满足您的要求。

  • 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"} />;
};

推荐阅读