监听本地存储reactjs中的更新 [英] Listening for updates in local storage reactjs

查看:871
本文介绍了监听本地存储reactjs中的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,要求用户提供输入.然后,我会将输入存储在本地存储中.

I have a form in which I ask users for their input. I will then store the input in the local storage.

let shape = {
   shape: shape,
   color: shapeColor,
   dimension: noOfDimension,
}
arr.push(shape)
window.localStorage.setItem("arr", JSON.stringify(arr))

现在,我有一个按钮,单击该按钮会弹出一个模态并显示存储的形状.形状数据可通过JSON.parse(localStorage.getItem("arr"))检索.但是问题是,当我再次添加新形状数据时,它不会反映在模态中(除非刷新).如何继续收听本地存储以进行更新?我尝试了以下代码:

Now I have a button in which when I click on it, a modal pops up and display the shapes stored. The shape data can be retrieved by JSON.parse(localStorage.getItem("arr")). However the problem is, when I were to add new shape data again, it will not be reflected in the modal (unless I refresh). How can I keep listening to the local storage for updates? I have tried the following code:

useEffect(()=>{
        function listenForStorage(){
            const item = localStorage.getItem('arr')
            if (item) {
              setShapeList(item)
            }
          }
          window.addEventListener('storage', listenForStorage)
          return () => {
            window.removeEventListener('storage', listenForStorage)
          }
    },[])

useEffect正在运行,但是不知何故window.addEventListener未被访问.

The useEffect is running, but somehow, the window.addEventListener is not being accessed .

推荐答案

您为localStorage设置的侦听器不适用于活动选项卡.在将需要执行的数据保存到localStorage的同时,您必须更新状态.

the listener you set for localStorage does not work for the active tab. You must update the state while saving the data you need to do to localStorage.

示例

https://codesandbox.io/s/gracious-nobel-ezp8f?file =/src/App.js

使用两个选项卡(控制台)进行测试

Test using two tabs (console)

https://ezp8f.csb.app/

这篇关于监听本地存储reactjs中的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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