给个营销型网站wordpress playlm版权
给个营销型网站,wordpress playlm版权,建设考试网站,直播软件下载网站一、先给面试官的“标准定义”#xff08;先声夺人#xff09; 防抖#xff08;debounce#xff09;#xff1a;在事件触发一段时间后才执行#xff0c;期间再次触发会重新计时 节流#xff08;throttle#xff09;#xff1a;在固定时间内只执行一次 这一句一定要先说…一、先给面试官的“标准定义”先声夺人防抖debounce在事件触发一段时间后才执行期间再次触发会重新计时节流throttle在固定时间内只执行一次这一句一定要先说。二、为什么在 React Hooks 里要“特别处理”问题本质闭包 重新渲染const fn () { console.log(count) }每次 render 都是新函数定时器 / 事件里用的可能是旧状态普通 JS 防抖在 Hooks 里会失效或拿到旧值三、Hooks 防抖推荐实现1️⃣ 最稳方案useRef useCallbackfunction useDebounceFn(fn, delay 300) { const timer useRefnumber | null(null) const fnRef useRef(fn) // 始终指向最新 fn解决闭包问题 fnRef.current fn const debounce useCallback((...args) { if (timer.current) { clearTimeout(timer.current) } timer.current window.setTimeout(() { fnRef.current(...args) }, delay) }, [delay]) return debounce }使用方式const onSearch useDebounceFn(value { fetchList(value) }, 500) input onChange{e onSearch(e.target.value)} /2️⃣ 面试官加分点使用 useRef 保存最新函数避免闭包导致状态不更新。四、Hooks 节流两种方式都要会方案一时间戳节流最稳定function useThrottleFn(fn, delay 300) { const lastTime useRef(0) const fnRef useRef(fn) fnRef.current fn return useCallback((...args) { const now Date.now() if (now - lastTime.current delay) { lastTime.current now fnRef.current(...args) } }, [delay]) }方案二定时器节流常被追问function useThrottleFn(fn, delay 300) { const timer useRefnumber | null(null) const fnRef useRef(fn) fnRef.current fn return useCallback((...args) { if (timer.current) return timer.current window.setTimeout(() { fnRef.current(...args) timer.current null }, delay) }, [delay]) }两种节流的区别面试官爱问方式特点时间戳立即执行定时器延迟执行五、为什么不用 lodash debounce可以用但要说清楚限制const debouncedFn useMemo( () debounce(fn, 300), [] )❌ 问题fn 变了debounce 不更新容易产生脏数据正确用法const fnRef useRef(fn) fnRef.current fn const debounced useMemo( () debounce((...args) fnRef.current(...args), 300), [] )六、Hooks 防抖节流常见坑必背❌ 错误写法const fn debounce(() { setCount(count 1) }, 300)问题每次 render 都创建新 debouncecount 永远是旧值✅ 正确认知防抖节流函数要只创建一次执行的函数要始终是最新的七、什么时候用防抖什么时候用节流防抖Debounce搜索框输入联想表单校验节流Throttle滚动resize拖拽八、面试终极总结一定要背React Hooks 下实现防抖节流关键不是 setTimeout而是用 useRef 解决闭包问题保证函数引用稳定且状态最新。