javascript - 为什么 localStorage 中的更改直到刷新才更新?

标签 javascript reactjs

我是使用 localStorage 的新手,我正在尝试使用 localStorage 来存储登录状态,以便在用户登录时显示注销按钮,在用户注销时显示登录按钮。

如果在重定向之前调用 localStorage,为什么它在重定向之前没有被更改?当我单击登录组件中的登录按钮时,应更新 localStorage,并应显示 app.js 中的注销导航栏链接,但直到刷新页面后才会显示。为什么会发生这种情况?如何在重定向到新页面时正确显示注销按钮?

登录.component.js

    onSubmit(e) {
        e.preventDefault()
        this.userdata = {
            username: this.state.username,
            password: this.state.password,
        };
        services.userlogin(this.userdata).then(res => {
                if (this._isMounted) {
                    console.log("Is mounted")
                    if (res === "Successfully authenticated user") {
                        // store the user in localStorage
                        console.log("changed");
                        localStorage.setItem('loggedIn', "true") -> loggedIn is set to true
                        localStorage.setItem('isloggingIn', "false") -> isLoggingIn is set to false
                        localStorage.setItem('username', this.userdata.username)
                    }
                    this.setState({errormessage: res, username:'', password:''});
                }
                else {
                    console.log("Is unmounted")
                }
        })
    }
    error()
    {
        if (this.state.errormessage === "Successfully authenticated user") {
            // store the user in localStorage
            return (<Redirect from="/login-component" to={{pathname: '/ShopDetail', state: this.state}}/>); -> Redirects to ShopDetail page but logout button isn't shown 

        }
        else{
            return (<span className="span">{this.state.errormessage}</span>);
        }
    }
    render() {
        return (
            <div className="div">
                <Form onSubmit={this.onSubmit} className="formWidth">
                    <Form.Group className="group" controlId="Username">
                        <Form.Label style={{display: 'flex', justifyContent: 'center'}}>Username</Form.Label>
                        <Form.Control type="text" value={this.state.username} onChange={this.onChangeusername}/>
                        {this.state.usernameerrormessage.length > 0 &&
                        <span className="span">{this.state.usernameerrormessage}</span>}
                    </Form.Group>
                    <Form.Group className="group" controlId="Password">
                        <Form.Label style={{display: 'flex', justifyContent: 'center'}}>Password</Form.Label>
                        <Form.Control type="text" value={this.state.password} onChange={this.onChangepassword}/>
                        {this.state.passworderrormessage.length > 0 &&
                        <span className="span">{this.state.passworderrormessage}</span>}
                    </Form.Group>
                    <Button variant="danger" size="lg" block="block" type="submit"> Login </Button>
                </Form>
                {this.error()}

            </div>
        );
    }
};

APP.js

constructor(){
    this.state = {isLoggingIn: localStorage.getItem('isloggingIn'), isLoggedIn: localStorage.getItem('loggedIn') ;
}
componentDidMount() {
        this.setState({isLoggingIn: localStorage.getItem('isloggingIn'), isLoggedIn: localStorage.getItem('loggedIn') });
    }
const {isLoggingIn, isLoggedIn} = this.state;
<Nav className="ml-auto">
          <Nav>
               {isLoggedIn==="false" && isLoggingIn==="false" && <Link to={'/login-component'} onClick={this.login} className="nav-link">Login</Link>}
          </Nav>
          <Nav>
               {isLoggedIn==="false" && isLoggingIn==="false" && <Link to={'/createuser-component'} className="nav-link">Sign up</Link>}
          </Nav>
          <Nav>
               {isLoggedIn==="true" && isLoggingIn==="false" && <Link to={'/'} onClick={this.logout} className="nav-link">Logout</Link>} -> ***isLoggedIn is set to true and isLoggingIn is set to false in async userlogin function but the change is not reflected here unless the page is refreshed***
          </Nav>
   </Nav>

我已经尝试解决这个问题很多天了,但我真的不明白为什么会发生这种情况。

最佳答案

您可以将函数引用从 App.js 传递到子组件。该函数获取一个新的状态值并执行 setState。在子组件中,您可以使用新值调用此函数

关于javascript - 为什么 localStorage 中的更改直到刷新才更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67614308/

相关文章:

javascript - 在reactJS中执行 "or statement"作为返回

javascript - 如何在 Javascript 中使用 Date 获取相对于当前时区的日期?

javascript - jquery 或 javascript 使列表框内容拖放

JavaScript:XMLSerializer.serializeToString() 的替代品?

javascript - React Native - Undefined 不是对象(评估 this.props.isLoggedIn.then)

javascript - 如何让 Formik 检测 Checkbox 字段何时被选中?

javascript - 获取 cookie 值 (javascript)

javascript - 使用 JS 更改图像路径的错误请求

reactjs - react 水平滚动条

javascript - <输入类型 ="file"> 的事件