【问题标题】:localStorage with React behaving very erratically带有 React 的 localStorage 表现非常不稳定
【发布时间】:2017-09-12 18:17:02
【问题描述】:

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

【问题讨论】:

    标签: reactjs redux local-storage react-redux


    【解决方案1】:

    原因是,localstoragestring 格式存储所有内容,即使您的booloen 值也会保存为'true''false',因此您需要检查@ 987654326@ 或使用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
        ....
    

    【讨论】:

    • 谢谢!我在两个报价上浪费了几个小时。应该阅读文档。
    • 很高兴,它帮助了你:)
    【解决方案2】:

    localStorage中的你的Item存储为String,你需要像字符串一样使用它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2015-09-13
      相关资源
      最近更新 更多