1.在utils中新建一个文件watchLocalStorage.ts
export default function dispatchEventStroage() { const signSetItem = localStorage.setItem localStorage.setItem = function (key, val) { let setEvent = new Event('setItemEvent') setEvent.key = key setEvent.newValue = val window.dispatchEvent(setEvent) // @ts-ignore signSetItem.apply(this, arguments) } }
2.页面初始化引入并调用 import dispatchEventStroage from './utils/watchLocalStorage'
//在需要的业务逻辑组件中调用监听store的和用户信息变化
dispatchEventStroage()
useEffect(() => {
//监听store的和用户信息变化
dispatchEventStroage()
const handleSetItemEvent = function (e: any) { if (e.key === 'UserData') { const newValue = e.newValue; const userData = newValue && JSONparse(newValue); const userId = userData?.userId; if (userId && !socket) { startWebSocket(userId) return } //退出登录 if (!userId && socket) { stopWebSocket() } } } window.addEventListener('setItemEvent', handleSetItemEvent) // document.addEventListener('visibilitychange', handleVisibilityChange); // 返回一个清理函数,以便在组件卸载时移除事件监听器 return () => { window.removeEventListener('setItemEvent', handleSetItemEvent) // window.removeEventListener('visibilitychange', handleVisibilityChange) } }, [socket])
标签:const,localeStorage,标签,userId,监听,window,dispatchEventStroage,newValue From: https://www.cnblogs.com/xiaoyaoweb/p/18534608