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])