flnxi-Wu/lib/hooks/useDebounce.ts
WuYongJie b7776d468a test: 添加防抖Hooks单元测试
- 创建useDebounce测试(9个测试用例)
  * 测试基本功能(初始值、延迟更新、快速变化)
  * 测试延迟时间配置(自定义延迟、0延迟)
  * 测试不同数据类型(字符串、数字、对象、数组)

- 安装测试依赖
  * jest-environment-jsdom - 提供DOM环境
  * @testing-library/dom - React测试库依赖

- 优化useDebounce实现
  * 添加组件卸载时的定时器清理
  * 确保状态更新的正确性

测试结果:9个测试用例全部通过
2025-12-13 15:38:03 +08:00

63 lines
1.5 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 { useEffect, useState } from 'react'
/**
* 防抖Hook - 延迟更新值直到用户停止输入
* @param value 需要防抖的值
* @param delay 延迟时间(毫秒)
* @returns 防抖后的值
*/
export function useDebounce<T>(value: T, delay: number = 300): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
// 设置定时器
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
// 清理函数:如果value在delay时间内再次改变,清除之前的定时器
return () => {
clearTimeout(handler)
}
}, [value, delay])
return debouncedValue
}
/**
* 防抖回调Hook - 创建一个防抖的回调函数
* @param callback 需要防抖的回调函数
* @param delay 延迟时间(毫秒)
* @returns 防抖后的回调函数
*/
export function useDebouncedCallback<T extends (...args: any[]) => any>(
callback: T,
delay: number = 300
): (...args: Parameters<T>) => void {
const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null)
useEffect(() => {
// 组件卸载时清理定时器
return () => {
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}, [timeoutId])
return (...args: Parameters<T>) => {
// 清除之前的定时器
if (timeoutId) {
clearTimeout(timeoutId)
}
// 设置新的定时器
const newTimeoutId = setTimeout(() => {
callback(...args)
setTimeoutId(null)
}, delay)
setTimeoutId(newTimeoutId)
}
}