新增 useSafeTimeout hook,页面隐藏时自动清理所有定时器。 10 个页面接入:daily-monitoring、exchange、family-add、 health/input、prescription detail/create、dialysis detail/create、 appointment detail/create。所有 fire-and-forget setTimeout 替换为 safeSetTimeout,避免页面切走后定时器回调在错误上下文执行。
24 lines
610 B
TypeScript
24 lines
610 B
TypeScript
import { useRef, useCallback } from 'react';
|
|
import { useDidHide } from '@tarojs/taro';
|
|
|
|
export function useSafeTimeout() {
|
|
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
|
|
|
const safeSetTimeout = useCallback((fn: () => void, ms: number) => {
|
|
const id = setTimeout(() => {
|
|
timers.current = timers.current.filter((t) => t !== id);
|
|
fn();
|
|
}, ms);
|
|
timers.current.push(id);
|
|
}, []);
|
|
|
|
const clearAll = useCallback(() => {
|
|
timers.current.forEach(clearTimeout);
|
|
timers.current = [];
|
|
}, []);
|
|
|
|
useDidHide(() => clearAll());
|
|
|
|
return { safeSetTimeout, clearAll };
|
|
}
|