react中如何监听localStorage的数据

4,892 阅读1分钟

在代码中遇到了需要在react中监听localStorage的数据,下意识想到的是按照useEffect监听useState变化那一套 代码如下:

useEffect(()=>{
        useData(localStorage.getItem('rightCartData'))
    },[localStorage.getItem('rightCartData')])

很显然并没有生效,示例不起作用的原因是和传递给 useEffect 的依赖数组有关,它决定了在组件渲染时是否重新运行(render),这意味着如果 localStorage 更改,但它必须 先渲染(render)。 解决这个问题的方法是设置对 localStorage 的订阅,监视变化并通知组件重新渲染。

于是从网上重新搜了下,找到了如下代码:

useEffect(() => {
        function rightCartData() {
            const item = JSON.parse(localStorage.getItem('rightCartData'))
            if (item) {
                setState(item);
            }
        }
        window.addEventListener('storage', rightCartData)
        return () => {
            window.removeEventListener('storage', rightCartData)
        }
    }, [])

在浏览器打开两个tab,确实能监听到localstorage的变化,但是由于我的需求是在同一个tab下的页面中监听localStorage,所以并不满足我的需求。

原因如下:qa.1r1g.com/sf/ask/3966…

最后找到解决方法,想要在当前页面监听localStorage的数据,只能重写setItem方法

const originalSetItem = sessionStorage.setItem;
		sessionStorage.setItem = function (key, newValue) {
			const setItemEvent = new Event('setItemEvent');
			setItemEvent[key] = newValue;
			window.dispatchEvent(setItemEvent);
			originalSetItem.apply(this, [key, newValue]);
		};
window.addEventListener('setItemEvent', changeWindowCommonMenuCollapsed);
		return () => {
			window.removeEventListener('setItemEvent', changeWindowCommonMenuCollapsed);
		};
                const changeWindowCommonMenuCollapsed = (e) => {
                console.log(e)
                }