侦听本地存储 reactjs 中的更新

IT技术 reactjs react-hooks local-storage addeventlistener
2021-05-25 07:23:32

我有一个表格,我在其中询问用户的意见。然后我会将输入存储在本地存储中。

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

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

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

useEffect 正在运行,但不知何故,window.addEventListener没有被访问。

2个回答

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

例子

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

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

https://ezp8f.csb.app/

试试这个:

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