refactor: streamline app initialization and enhance WebSocket cleanup logic

This commit is contained in:
xmk23333
2025-10-20 13:15:51 +08:00
Unverified
parent a0ef64cda8
commit b77cc012e1
16 changed files with 582 additions and 554 deletions

35
src/hooks/use-cleanup.ts Normal file
View File

@@ -0,0 +1,35 @@
import { useEffect, useRef } from "react";
/**
* 资源清理 Hook
* 用于在组件卸载或窗口关闭时统一清理资源
*/
export const useCleanup = () => {
const cleanupFnsRef = useRef<Set<() => void>>(new Set());
const registerCleanup = (fn: () => void) => {
cleanupFnsRef.current.add(fn);
return () => {
cleanupFnsRef.current.delete(fn);
};
};
const cleanup = () => {
cleanupFnsRef.current.forEach((fn) => {
try {
fn();
} catch (error) {
console.error("[资源清理] 清理失败:", error);
}
});
cleanupFnsRef.current.clear();
};
useEffect(() => {
return () => {
cleanup();
};
}, []);
return { registerCleanup, cleanup };
};

View File

@@ -87,7 +87,12 @@ export const useConnectionData = () => {
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
ws.current?.close();
ws.current = null;
};
},
{

View File

@@ -13,9 +13,26 @@ export const useListen = () => {
unlistenFns.current.push(unlisten);
return unlisten;
};
const removeAllListeners = () => {
unlistenFns.current.forEach((unlisten) => unlisten());
unlistenFns.current = [];
const errors: Error[] = [];
unlistenFns.current.forEach((unlisten) => {
try {
unlisten();
} catch (error) {
errors.push(error instanceof Error ? error : new Error(String(error)));
}
});
if (errors.length > 0) {
console.warn(
`[useListen] 清理监听器时发生 ${errors.length} 个错误`,
errors,
);
}
unlistenFns.current.length = 0;
};
const setupCloseListener = async function () {
@@ -26,6 +43,7 @@ export const useListen = () => {
return {
addListener,
removeAllListeners,
setupCloseListener,
};
};

View File

@@ -120,7 +120,12 @@ export const useLogData = () => {
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
ws.current?.close();
ws.current = null;
};
},
{

View File

@@ -63,7 +63,12 @@ export const useMemoryData = () => {
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
ws.current?.close();
ws.current = null;
};
},
{

View File

@@ -69,7 +69,12 @@ export const useTrafficData = () => {
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
ws.current?.close();
ws.current = null;
};
},
{