自定义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();//重新请求接口数据(自定义) } }, []);
使用方法:
标签:undefined,自定义,dom,useResume,handleVisibleChange,visibilityChange,hidden,document 来源: https://www.cnblogs.com/yujiawen/p/15401129.html