Live2D

自定义dom重现函数useResume

处理逻辑,经常需要在dom重现使用时回掉函数(重新请求数据,重新定义状态等),以下是工作中常用的一个重新回掉函数的定义:
 
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();//重新请求接口数据(自定义)
   }
}, []);
 

 

posted @ 2021-10-13 10:55  喻佳文  阅读(56)  评论(0编辑  收藏  举报