首页 > 解决方案 > 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可以访问,否则它将重定向到显示错误的某个页面,使用另一条路线。我不知道该怎么做。

标签: javascriptreactjsreact-router

解决方案


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 },
            }}
          />
        );
      }}
    />
  );
}

推荐阅读