![](/img/trans.png)
[英]How do i re-run useEffect hook if the localstorage value has been changed?
[英]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)
}
}, [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.