2017-07-14 105 views
1

每次用户登录时,即使有页面重新载入,我也希望状态保持为'真'。 状态初始设置为false,(让_authed = false)。 但是,当我重新加载页面,它会回到假,这是索引页。如何在使用本地存储维护页面刷新后的状态

我做了什么 当用户登录时,我保存用户的细节的localStorage,并在用户注销时,我清除了localStorage的,我又把它设置为false。 (这工作正常)

在setAuthed()函数中,我试图检查我存储在localStorage中的用户是否不为null,它应该保持authed变量为true。

但是,当我刷新页面时,它不工作。有什么,我做错了吗?帮助赞赏。

let _authed = false; 

// User logs in, set user in localStorage 
saveUser(user){ 
    _user = user; 
    localStorage.setItem('user', JSON.stringify(user)) 
}, 

//User clicks logout, set state to false 
setLogout(){ 
    _authed = false; 
    localStorage.clear() 
}, 

// If there is a user in local storage, always set state to true 
setAuthed(){ 
    if (localStorage.getItem("user") !== null) { 
     _authed = true; 
     } 
}, 


getAuthed(){ 
    return _authed; 
}, 
+0

你在哪里调用'setAuthed'? –

+0

调用这些函数的实际React代码在哪里?这些功能在哪里生活? (希望不是全局范围,而是一些库对象,您正在导入/需要您的React组件?) –

+0

它实际上是一种流量架构,代码驻留在商店中 – Wes

回答

2

您可以使用React lifecycle方法读取和写入某种持久状态。在这里我写了一个小例子来展示它。

class Root extends React.Component { 
 
    state = { 
 
    isLoggedIn: false 
 
    } 
 
    
 
    componentDidMount() { 
 
    const persisState = localStorage.get('rootState'); 
 
    
 
    if (persistState) { 
 
     try { 
 
     this.setState(JSON.parse(pesistState)); 
 
     } catch (e) { 
 
     // is not json 
 
     } 
 
    } 
 
    } 
 
    
 
    componentWillUnmount() { 
 
    localStorage.set('rootState', JSON.stringify(this.state); 
 
    } 
 

 
    render() { 
 
    return (
 
     <div> 
 
     {this.props.children} 
 
     </div> 
 
    ) 
 
    } 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

相关问题