簡體   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