localeStorage 当前标签页变化监听不到,只能监听不同标签页变化,自己写方法监听

 

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

  

posted @ 2024-11-08 10:38  红苹果学园  阅读(3)  评论(0编辑  收藏  举报