javascript - 存储事件监听器不能与本地存储的任何更新一起工作
问题描述
在我的 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
});
}
});
}
我无法重置本地存储,也无法收听本地存储的未来变化
解决方案
存储事件不会在当前文档中触发。它用于通知您应用程序的其他打开的选项卡有一些更改。
当在另一个文档的上下文中修改了存储区域(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);
推荐阅读
- swift - 查询以计算追随者人数 swift 4
- javascript - 基于标记的中心传单地图
- javascript - 反应历史推送不渲染组件
- php - 如何使用 mpdf 将 html 中的页面方向设置为 pdf?
- angular - 如何过滤角材料表中的多语言文本?
- amazon-web-services - 如何使用 cli 命令获取运动流列表
- firebase - 比较 'currentUser?.uid' 到 childByAutoIds
- c# - 将缺失的日期添加到没有销售的 JSON
- linux-kernel - 元数据日志如何停止写入系统调用?
- matplotlib - Matplotlib:设置animation.rc参数