简体   繁体   English

如果 localstorage 值已更改,我如何重新运行 useEffect hook?

[英]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:问题:

  • I cannot pass 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:我试过的:

  • I have looked at this answer on SO, but my situation is a bit complex as I'm loading the entire items to a variable first(I'm not aware of any better alternatives)我已经在 SO 上查看了这个答案,但是我的情况有点复杂,因为我首先将整个项目加载到一个变量中(我不知道有什么更好的选择)
  • I have tried to put the state value in the dependency list, but it doesn't work and goes to infinite loop.我试图将 state 值放入依赖列表中,但它不起作用并进入无限循环。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM