How to listen to localstorage in react.js(如何在 react.js 中收听 localstorage)
问题描述
我在使用从本地存储中的数组获取数据的组件时遇到问题.它在页面加载时获取初始数据,但是当 localstorage 更改时如何更新?
I'm having a problem with a component that gets data from an array in localstorage. It gets the initial data when the page loads, but how do I update when localstorage is changed?
推荐答案
根据 Mozilla 的 Web API 文档,有一个 StorageEvent
会在对 Storage
进行更改时触发对象.
Per Mozilla's Web API docs there's a StorageEvent
that gets fired whenever a change is made to the Storage
object.
我在我的应用程序中创建了一个警报组件,只要对特定的 localStorage
项进行更改,该组件就会关闭.我会添加一个代码片段供您运行,但由于跨域问题,您无法通过它访问 localStorage.
I created an Alert component within my application that would go off whenever a change was made to a specific localStorage
item. I would've added a code snippet for you to run but you can't access localStorage through it due to cross-origin issues.
这篇关于如何在 react.js 中收听 localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!