繁体   English   中英

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

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

在我的反应应用程序中,我将用户数据过滤器保存到 localStorage 中。 我想在更改数据时使用效果。 如何正确触发该效果? 我试过这个:

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

localStorage.activeEstateListFilter不会触发效果..

您是否在 localStorge 中设置了值? 如果设置它然后:

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)
  }
}, [])

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

暂无
暂无

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

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