简体   繁体   English

localStorage 中的值更改时如何使用效果?

[英]How to useEffect when value in localStorage changed?

In my react app i'm saving user data filters into localStorage.在我的反应应用程序中,我将用户数据过滤器保存到 localStorage 中。 I want to useEffect, when that data was changed.我想在更改数据时使用效果。 How to correctly trigger that effect?如何正确触发该效果? I tried this:我试过这个:

useEffect(() => {
    if (rawEstateObjects.length && localStorage.activeEstateListFilter) {
      const activeFilter = JSON.parse(localStorage.activeEstateListFilter)
      if (activeFilter.length) {
        applyFilter(activeFilter)
      }
    }
  }, [rawEstateObjects, localStorage.activeEstateListFilter])

but localStorage.activeEstateListFilter doesn't triggers the effect..localStorage.activeEstateListFilter不会触发效果..

did you set value in localStorge?您是否在 localStorge 中设置了值? if set it then:如果设置它然后:

useEffect(() => {
  function activeEstateList() {
    const item = localStorage.getItem('activeEstateListFilter')

    if (rawEstateObjects.length && item) {
      const activeFilter = JSON.parse(localStorage.activeEstateListFilter)
      if (activeFilter.length) {
        applyFilter(activeFilter)
      }
    }
  }

  window.addEventListener('storage', activeEstateList)

  return () => {
    window.removeEventListener('storage', activeEstateList)
  }
}, [])

refrence answer: https://stackoverflow.com/a/61178371/7962191参考答案: https : //stackoverflow.com/a/61178371/7962191

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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