Files
czzj-app/src/hooks/use-page-show-refresh.ts
2026-10-29 10:09:43 +08:00

45 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { onShow } from '@dcloudio/uni-app'
function clearStaleNativeLoading() {
try {
uni.hideLoading()
} catch {
// 部分端无 loading 时 hideLoading 可能抛错,忽略即可
}
}
/**
* 页面再次显示时执行刷新(从子页返回、切换 Tab 等)。
* - skipInitialShow:首屏由 onLoad 加载时设为 true,避免与 onLoad 重复请求
* - 自动清掉残留的原生 showLoading(避免改名等流程的 loading 串到其他页)
* - 短防抖 + 进行中跳过,避免连点返回/快速切页触发重复请求或闪提示
*/
export function usePageShowRefresh(
handler: () => void | Promise<void>,
options?: { skipInitialShow?: boolean; debounceMs?: number },
) {
let skipFirst = Boolean(options?.skipInitialShow)
let inflight = false
let timer: ReturnType<typeof setTimeout> | undefined
const debounceMs = options?.debounceMs ?? 280
onShow(() => {
clearStaleNativeLoading()
if (skipFirst) {
skipFirst = false
return
}
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
if (inflight) return
inflight = true
Promise.resolve()
.then(() => handler())
.catch(() => {})
.finally(() => {
inflight = false
})
}, debounceMs)
})
}