localStorage中的值发生变化时如何使用Effect?

Who*_*sDT 5 javascript local-storage reactjs

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

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

localStorage.activeEstateListFilter不触发效果..

小智 0

您在 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)
  }
}, [])
Run Code Online (Sandbox Code Playgroud)

参考答案:/sf/answers/4282486001/