如何聆听本地存储的价值变化做出反应? [英] How to listen to localstorage value changes in react?

查看:60
本文介绍了如何聆听本地存储的价值变化做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户登录时显示一个按钮.如果用户未登录,那么我不显示按钮.用户登录时,我将设置本地存储值.当我在登录组件中设置本地存储时,Header组件必须侦听该事件并显示按钮.我正在使用addEventListener进行监听.但它没有监听.

I want to show a button when user is logged.If user is not logged then I m not showing button.When user logged i will set local storage values.when i set local storage in login Component,Header component must listen to that event and show the button.I m using addEventListener for listening.But its not listening.

我不知道在标题Component中侦听的位置.

I don't know where to listen in header Component.

//HeaderComponent(header.js):

// HeaderComponent(header.js):

class HeaderComponent extends Component {
    componentDidMount(){
        if(typeof window!='undefined'){
            console.log(localStorage.getItem("token"));
            window.addEventListener("storage",function(e){
               this.setState({ auth: true});
            })
        }
    } 
    render() {

    return (
        <div className="header">
            <div className="container">
                <div className="header-content">
                    <img src={logo} alt="logo"></img>
                    <div className="nav-links" >
                        <ul >
                            <li>Home</li>
                            <li>About</li>
                            <li>Services</li>
                            <li><NavLink activeClassName="active" to="/upload" >Upload</NavLink></li>
                            <li><NavLink activeClassName="active" to="/signup"> Sign Up</NavLink></li>


                           { this.state.auth? <li onClick={this.onLogout}>Logout</li> :null}

                        </ul>
                    </div>
                </div>
            </div>

        </div>
    );
   }  
}

//loginComponent(login.js)

//loginComponent(login.js)

class LoginComponent extends Component {
    constructor(props) {
        super(props);
        this.onSubmit = this.onSubmit.bind(this);
    }
    onSubmit(event) {
        const data = {
            username: document.getElementById('name').value,
            password: document.getElementById('password').value
        }
        axios.post(`http://localhost:4000/user/login`, data).then(res => {
            this.props.history.push("/");
            localStorage.setItem("token",res.data.token);
            localStorage.setItem("auth",true);
        }).catch(err => console.log(err));
    }


    render() {
        return (
            <section class="log-in">
                <div class="card-col">
                    <form>
                        <h3>LOG IN</h3>
                        <div class="form-controls">
                            <input id="name" type="text" placeholder="username" class="input"></input>
                        </div>
                        <div class="form-controls">
                            <input id="password" type="password" placeholder="password" class="input"></input>
                        </div>
                        <button type="submit" onClick={this.onSubmit} class="button" >Log in</button>
                    </form>
                </div>

           </section>

        )
    }

}

推荐答案

请注意两点

  1. storage 事件仅在在两个浏览器选项卡中打开同一应用程序时才起作用(该事件用于在同一应用程序的不同选项卡之间交换信息).当同一页面上同时显示两个组件时,存储事件不会触发.

  1. storage event works only when the same application opened in two browser tabs (it is used to exchange info between different tabs of the same app). Storage event will not fire when both components shown on the same page.

添加事件列表器时,您传递的是 function(),而不是数组函数. function()不会捕获 this ,因此您应该明确地 bind(this)或将其更改为箭头功能.

When adding event listerner, you're passing function(), not array function. function() doe not capture this so you should explicitly bind(this) or change it to arrow function.

例如

window.addEventListener("storage",(function(e){
       this.setState({ auth: true});
    }).bind(this));

或者使用箭头功能

window.addEventListener("storage",(e) => {
       this.setState({ auth: true});
    });

这很简单示例.

请确保在两个标签(相同的链接)中将其打开.将值存储在一个选项卡中,然后在另一个选项卡中查看该值.

Be sure to open it in two tabs (the same link). Store value in one tab and see this value in another tab.

这篇关于如何聆听本地存储的价值变化做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆