首页 > 解决方案 > 存储事件监听器不能与本地存储的任何更新一起工作

问题描述

在我的 componentDidMount 中,我试图删除一个 localstorage 项目并添加一个事件侦听器以进一步更改 localstorage 并且它不起作用

  componentDidMount() {
    localStorage.removeItem("receivedLocation");
    window.addEventListener("storage", event => {
      console.log("Event listener triggered");
      if (event.key === "receivedLocation" && event.newValue === true) {
        this.setState({
          receivedLocation: true
        });
      }
    });
  }

而如果我删除更新项目它工作正常。

  componentDidMount() {
    window.addEventListener("storage", event => {
      console.log("Event listener triggered");
      if (event.key === "receivedLocation" && event.newValue === true) {
        this.setState({
          receivedLocation: true
        });
      }
    });
  }

我无法重置本地存储,也无法收听本地存储的未来变化

标签: javascriptreactjsaddeventlistener

解决方案


存储事件不会在当前文档中触发。它用于通知您应用程序的其他打开的选项卡有一些更改。

当在另一个文档的上下文中修改了存储区域(localStorage 或 sessionStorage)时,会触发 Window 接口的存储事件

如果您尝试通知当前选项卡中的其他组件,则可以使用DOMEvents

const event = new Event('EVENT_NAME', { detail: { yourPayload }});
window.dispatchEvent(event);

// in your component
window.addEventListener('EVENT_NAME', configChangedHandler, false);

// cleanup
window.removeEventListener('EVENT_NAME', configChangedHandler);


推荐阅读