如何使反应路由器受到保护?

时间:2020-05-31 10:44:28

标签: reactjs

我只是从角度转向反应,我正在创建动态路线,但问题是我不知道如何在下面将其设为私有代码。

请帮助我解决这个问题。

const routes = [
  {
    path: "/",
    children: Dashboard,
    exact: true,
    authGuard: true,
  },
];

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <Route
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        ))}
      </Switch>
    </Router>
  );
};

const PrivateRoute = ({ children, ...rest }) => {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        sessionStorage.getItem("token") ? (
          children
        ) : (
          <Redirect to={{ pathname: "/login", state: { from: location } }} />
        )
      }
    ></Route>
  );
};

export default Routes;

任何解决方案表示赞赏!

1 个答案:

答案 0 :(得分:1)

您可以呈现包含逻辑的PrivateRoute,而不是在映射时呈现Route组件

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => (
          <PrivateRoute
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        ))}
      </Switch>
    </Router>
  );
};

由于您将authGurad指定为json中的属性,因此可以使用它来选择要渲染的Route。

const Routes = () => {
  return (
    <Router>
      <Switch>
        {routes.map((route, index) => {
        const Component = route.authGuard? PrivateRoute: Route;
        return (
          <Component
            key={index}
            path={route.path}
            exact={route.exact}
            children={<route.children />}
          />
        )})}
      </Switch>
    </Router>
  );
};