Reactjs 带有React的localStorage的行为非常不稳定

Reactjs 带有React的localStorage的行为非常不稳定,reactjs,redux,local-storage,react-redux,Reactjs,Redux,Local Storage,React Redux,我试图仅在用户登录时显示配置文件组件。我使用localStorage来存储用户是否登录。即使布尔userLoggedIn为false,也会呈现组件。我肯定我犯了一个非常愚蠢的错误。提前道歉 我使用本地状态来决定是否要渲染组件。加载组件时,我调用: constructor(props){ super(props); this.state={showDropdown: false, userLoggedIn: false}; } 然后,当组件装载时,我将user

我试图仅在用户登录时显示配置文件组件。我使用localStorage来存储用户是否登录。即使布尔userLoggedIn为false,也会呈现组件。我肯定我犯了一个非常愚蠢的错误。提前道歉

我使用本地状态来决定是否要渲染组件。加载组件时,我调用:

 constructor(props){
        super(props);
        this.state={showDropdown: false, userLoggedIn: false};
 }
然后,当组件装载时,我将userLoggedIn状态设置为true或false

componentDidMount(){
    this.setState({userLoggedIn:            
    localStorage.getItem("userLoggedIn")});
}
用户登录时,我使用以下命令将localStorage布尔值设置为true:

localStorage.setItem('userLoggedIn', true);
这发生在动作创建者中。我使用开发工具检查本地存储以验证这是否有效

然后,在我的组件中,我通过调用函数来呈现:

{this.renderProfileButton()}
功能是:

renderProfileButton(){                  

    console.log("renderProfileButton:"
     +localStorage.getItem("userLoggedIn"));
    if(this.state.userLoggedIn){
            return(
                <ProfileContainer userLoggedIn=  {this.state.userLoggedIn}> 
                    <IconImage src="/static/profilepic.png" onClick=      
                      {()=>{this.toggleDropdown()}} />
                        <ProfileDropdown showDropdown=     
                          {this.state.showDropdown}>
                        <NavBarArrowDiv/>
                        <DropdownContent>
                            <LabelGrey onClick={()=>{this.logOutUser();
                                this.toggleDropdown();}}> Logout
                            </LabelGrey>
                        </DropdownContent>
                    </ProfileDropdown>
                </ProfileContainer>
            );
        }
}
原因是,localstorage以字符串格式存储所有内容,甚至您的booloen值也将保存为“true”、“false”,因此您需要检查字符串或使用JSON.parse再次将其转换为布尔值,如下所示:

componentDidMount(){
    this.setState({userLoggedIn:            
         JSON.parse(localStorage.getItem("userLoggedIn"))
    });
}
renderProfileButton(){                  

    console.log("renderProfileButton:" , localStorage.getItem("userLoggedIn"));
    if(this.state.userLoggedIn == 'true'){ //check 'true' here
    ....
或者在该函数中检查字符串,如下所示:

componentDidMount(){
    this.setState({userLoggedIn:            
         JSON.parse(localStorage.getItem("userLoggedIn"))
    });
}
renderProfileButton(){                  

    console.log("renderProfileButton:" , localStorage.getItem("userLoggedIn"));
    if(this.state.userLoggedIn == 'true'){ //check 'true' here
    ....
如果localStorage中的项存储为字符串,则需要将其作为字符串使用

componentDidMount(){
    var userLoggedIn = (localStorage.getItem("userLoggedIn") === "true" ) ? true: false
    this.setState({userLoggedIn:            
    userLoggedIn});
}

谢谢我在两段引语上浪费了几个小时。我应该读一下这些文件。很高兴,它帮助了你: