![](/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.