[英]How do i re-run useEffect hook if the localstorage value has been changed?
I'm trying to re-run the useEffect hook based if any new item has been added to the localstorage.如果有任何新项目已添加到本地存储,我将尝试重新运行 useEffect 挂钩。
My useEffect looks like this:我的 useEffect 看起来像这样:
useEffect(() => {
//getting all localstorage items and setting to a variable
const localStorageItems = { ...localStorage }
// filtering out the localstorage items for keys that only starts with "HTTP" & pushing it to the state called "testData" using setTestData useState hook.
const filteredByKey = Object.fromEntries(
Object.entries(localStorageItems).filter(([key, value]) => {
if (key.startsWith("http")) {
testArr2.push({ urls: [key, value] })
// setTestData({ urls: [key, value] })
setTestData((prev) => [...prev, { key, value }])
}
})
)
}, [])
My problem is when I hit a button(adding a new data) this useEffect should ideally re-run, setting the latest data to the "testData" state.我的问题是当我点击一个按钮(添加新数据)时,这个 useEffect 最好重新运行,将最新数据设置为“testData”state。
The Problem:问题:
window.localstorage
to the useEffect's array dependency list, as it is external variable I believe and react doesn't allow it.window.localstorage
传递给 useEffect 的数组依赖列表,因为我相信它是外部变量并且 React 不允许这样做。 What I have tried:我试过的:
Please help.请帮忙。 Thanks for reading this far.
感谢您阅读到这里。
i can give you a work around for this use case, create react context that syncs with localStorage
.我可以为您解决此用例,创建与
localStorage
同步的反应上下文。 you can use the context as a useEffect
dependency.您可以将上下文用作
useEffect
依赖项。 sync means, take the value from localStorage
at starting and update the context along with the localStorage
from your app. sync 意味着,在启动时从
localStorage
中获取值,并从您的应用程序中更新上下文以及localStorage
。
Define a state that holds the local storage value and pass it as a useEffect parameter.定义一个保存本地存储值的 state 并将其作为 useEffect 参数传递。
const [localStorageData, setLocalStorageData] = useState([]);
useEffect(() => {
// Your codes
}, [localStorageData])
you can use 'storage' event listener您可以使用“存储”事件侦听器
window.addEventListener('storage', function(e) {
if (e.newValue) {
console.log('new data is saved ...')
// ...... your code
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.