带有 React 的 localStorage 表现非常不稳定

localStorage with React behaving very erratically

我试图仅在用户登录时显示配置文件组件。我正在使用 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);

这发生在动作创作者身上。我使用开发工具检查 localstorage 以验证这是否有效。

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

{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>
            );
        }
}

原因是,localstoragestring 格式存储所有内容 ,甚至您的 booloen 值也会被保存为 'true' , 'false', 因此您需要检查 string 或使用 JSON.parse 再次将其转换为 boolean, 如下所示:

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

或者在 function 里面检查 string,像这样:

renderProfileButton(){                  

    console.log("renderProfileButton:" , localStorage.getItem("userLoggedIn"));
    if(this.state.userLoggedIn == 'true'){ //check 'true' here
    ....

您在 localStorage 中的项目存储为 String,您需要像字符串一样使用它作为

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