pro-components icon indicating copy to clipboard operation
pro-components copied to clipboard

antd 如何监听浏览器返回事件

Open yangyan123 opened this issue 1 year ago • 0 comments
trafficstars

提问前先看看:

https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way/blob/main/README-zh_CN.md

🧐 问题描述

antd 如何监听浏览器返回事件,我现在使用以下几种方式,但是hashchange和popstate这两个事件我监听不到

💻 示例代码

const myHistory = useHistory();

useEffect(() => { const handle = () => { console.log(2132444); localStore.setItem('addDetail', JSON.stringify(formRef.current?.getFieldsValue())); }; const visibHandle = () => { if (document.visibilityState === 'hidden') { localStore.setItem('addDetail', JSON.stringify(formRef.current?.getFieldsValue())); } };

// // beforeunload popstate visibilitychange
window.addEventListener('beforeunload', handle);
window.addEventListener('hashchange', handle);
window.addEventListener('popstate', handle);
window.addEventListener('visibilitychange', visibHandle);

return () => {
  window.removeEventListener('beforeunload', handle);
  window.removeEventListener('hashchange', handle);
  window.removeEventListener('popstate', handle);
  window.removeEventListener('visibilitychange', visibHandle);
};

}, []);

useEffect(() => { const unlisten = myHistory.listen(() => { // 在这里可以执行你的逻辑 localStore.setItem('addDetail', JSON.stringify(formRef.current?.getFieldsValue())); });

return () => {
  // 组件卸载时取消监听
  unlisten();
};

}, [myHistory]);

🚑 其他信息

我的版本是 image

yangyan123 avatar Mar 05 '24 13:03 yangyan123