简体   繁体   中英

Javascript React redirect if session variable is set

I am using react. I have a login page which I don't want the user to be able to visit if a variable is set to true.

I am using sessionStorage after the user logs in and setting a variable to true:

 sessionStorage.setItem('loggedin', 'true');

My problem is that the use is still able to visit the login page.

How do I disallow the use to visit this page if loggedin is set to true?

Here's my current App Component:

class App extends React.Component {

  render() {
    return (
      <Router>
        <div>
          <Nav />
          <Route exact path="/" component={Home} />
          <Route exact path="/contact" component={contact} />
          <Route path="/login" component={Login} />
        </div>
      </Router>
    )
  }

In main component ( <App/> ), put the logic code inside ComponentWillMount() or constructor to check loggedIn status, then put inside render() condition to render page or not.

UPDATE: you want to stop people who logged in to access login page, I update my answer: in LoginComponent check if loggedIn , do redirect to root. Router in my example is ReactRouter .

eg :

Class LoginComponent extends React.Components {
    constructor(props) {
       super(props);
       this.loggedIn = sessionStorage.getItem('loggedin') === 'true';

    }

    render() {
       // my example using reactRouter
       if(!this.loggedIn) {
           return <Redirect to='/'/>;
       }
       return (<div>Your Login content</div>)
    }

}

You can pass a onEnter function to Route Component which will be called when a user hits the corresponding URL. Just check here that user is loggedin. If he is loggedin and wants to go to Login component, just redirect to your Home component otherwise go as it is.

export function onEnter(nextState, transition, callback) {
  const { pathname } = nextState.location
  const isLoggedIn = sessionStorage.getItem('loggedin') === 'true'
  if (pathname === '/login' && isLoggedIn) {
    transition('/') //redirect to Home component
  }
  return callback() // go as it is.
}


class App extends React.Component {

  render() {
    return (
      <Router>
        <div>
          <Nav />
          <Route exact path="/" component={Home} onEnter={onEnter}/>
          <Route exact path="/contact" component={contact} onEnter={onEnter}/>
          <Route path="/login" component={Login} onEnter={onEnter}/>
        </div>
      </Router>
    )
  }
}

Note: I have tested in react-router version 3.0 not higher.

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