2017-06-29 68 views
0

我有一个sessionstorage变量被称为loggedIn。Javascript React sessionstorage如果登录更改导航链接

如果设置为true(用户登录)我需要登录链接更改为:

<li><a href="" onClick('logout()')>Logout</li> 

这样我就可以使用注销方法将sessionStorage的variale更改为false。

下面是当前的代码:

class Nav extends React.Component { 
constructor(props) { 
    super(props); 
    this.isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true'; 
    this.state = { 
     message: 'You are Logged In', 
    }; 

} 

logout() { 
    sessionStorage.setItem('loggedIn', false); 
    // then update changes 
} 

    render() { 
    return (
     <ul> 
     <li><a href="#home">Home</li> 
     <li><a href="#login">Login</li> // If Not logged in change this to <li><a href="" onClick('logout()')>Logout</li> 
     <li></li> // If loggedin the show Message here 
     </ul> 
    ) 
    } 

我怎样才能做到这一点?

回答

1

通过state变量保持用户登录状态,将isLoggedIn变量存储在state中,并根据用户登录状态更新该变量。

使用conditional renderingrender不同元素的基础上isLoggedIn的值。

另一个变化是你定义在注销单击事件的方式,它应该是:

onClick={this.logout} 

,并绑定在constructor此方法。

检查文档:How to handle events in JSX

写这样的:

class Nav extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
     message: 'You are Logged In', 
     isLoggedIn: sessionStorage.getItem('isLoggedIn') === 'true' 
     }; 
     this.logout = this.logout.bind(this); 
    } 

    logout() { 
    sessionStorage.setItem('loggedIn', false); 

    //here update the state variable 

    this.setState({ 
     isLoggedIn: false 
    }); 
    } 

    render() { 
    return (
     <ul> 
     <li><a href="#home">Home</li> 

     {/*use condition here if user is loggedin then render the logout otherwise login button*/}   

     {this.state.isLoggedIn ? 
      <li><a href="" onClick={this.logout}>Logout</li> 
      : 
      <li><a href="#login">Login</li> 
     } 

     <li></li> 
     </ul> 
    ) 
    } 
} 
0

您可以使用三元运算符的JSX是这样的:

{this.isLoggedIn ? <li><a href="" onClick={this.logout}>Logout</a></li> : <li><a href="#login">Login</a></li>} 

,如果你想要一些的messge如果条件是真的,那么你可以这样做:

{this.isLoggedIn && <li>Your message</li>} 

如果将状态存储为isLoggedIn会更好。

欲了解更多详情,请点击这里https://facebook.github.io/react/docs/conditional-rendering.html