简体   繁体   中英

ReactJS -> how do I make restricted routes?

I have a couple of react routes that look like this:

<Route exact path='/Home' component={Products}/>
<Route path='/Login' component={Login}/>
<Route path='/Register' component={Register}/>
<Route path='/ProfilePage' component={ProfilePage}/>

And I would like to make it so that the profilepage route would be accessible only by a user that has logged in but I have almost no ideas as to how that would happen. I've thought of creating a state that would keep the loginStatus until a cookie with the loginStatus expires(for example after a week or so) and then somehow if the loginStatus='logged' then the profilepage router will be accessible otherwise it would redirect to some page showing an error, using another route. I've got no idea how to do that though.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM