import { useEffect } from "react"; export default function useResume(fn: any, deps: Array<any>) { function getResumeEventInfo() { // 设置隐藏属性和改变可见属性的事件的名称 let hidden; let visibilityChange; if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support hidden = 'hidden'; visibilityChange = 'visibilitychange'; } else if (typeof document['msHidden'] !== 'undefined') { hidden = 'msHidden'; visibilityChange = 'msvisibilitychange'; } else if (typeof document['webkitHidden'] !== 'undefined') { hidden = 'webkitHidden'; visibilityChange = 'webkitvisibilitychange'; } return { hidden, visibilityChange }; } useEffect(() => { const { visibilityChange, hidden } = getResumeEventInfo(); const handleVisibleChange = () => { // 页面可见 fn(document[hidden]); } document.addEventListener(visibilityChange, handleVisibleChange, false); return () => { document.removeEventListener(visibilityChange, handleVisibleChange, false); } }, [...deps]); }useResume((hidden) => { if (!hidden ) { retryFetch();//重新请求接口数据(自定义) } }, []);
使用方法: