如何在 React.js 中的 localStorage 发生任何更改时立即更新状态 [英] How to instantly update state when any changes into the localStorage in React.js

查看:22
本文介绍了如何在 React.js 中的 localStorage 发生任何更改时立即更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

localStorage myCart 数组发生任何变化时,如何立即更新购物车页面数据?下面是我的代码

const [cart, setCart] = React.useState([])React.useEffect(() => {setCart(JSON.parse(localStorage.getItem('myCart')) || [])}, [])

cart 会在页面重新加载时更新,但不会在新项目添加或更新任何现有项目时更新!

我怎样才能做到这一点,即 cart 如果对 'localStorage` 有任何更改,会立即更新?

提前致谢.

解决方案

你可以添加一个 eventlistenerlocalstorage 事件

React.useEffect(() => {window.addEventListener('storage', () => {//当本地存储发生变化时,将列表转储到//控制台.setCart(JSON.parse(localStorage.getItem('myCart')) || [])});}, [])

<块引用>

当一个存储区域触发Window界面的存储事件(localStorage) 已被修改.存储事件仅在其他窗口进行更改时触发.

.

How to update cart page data instantly when any changes in the localStorage myCart array? Here is my code below

const [cart, setCart] = React.useState([])

React.useEffect(() => {
    setCart(JSON.parse(localStorage.getItem('myCart')) || [])
}, [])

the cart is updated when the page reloads but not when new item adds or updates any existing items!

How can I achieve that, which is cart update instantly if any changes into 'localStorage`?

Thanks in advance.

解决方案

You can add an eventlistener to the localstorage event

React.useEffect(() => {
    
window.addEventListener('storage', () => {
  // When local storage changes, dump the list to
  // the console.
   setCart(JSON.parse(localStorage.getItem('myCart')) || [])   
});

   
}, [])

The storage event of the Window interface fires when a storage area (localStorage) has been modified.The storage event is only triggered when a window other than itself makes the changes.

.

这篇关于如何在 React.js 中的 localStorage 发生任何更改时立即更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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