京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

react组件中debounce防抖功能失效问题解决办法

2024-11-2 22:36| 发布者: 8b79| 查看: 64| 评论: 0

摘要: 目次一、问题背景二、解决办法三、拓展一、问题背景 [code]import { debounce } from 'lodash'; const [searchKey, setSearchKey] = useState(''); // 防抖函数 const debounceList = debounce(getList, 500);[/
目次

一、问题背景

[code]import { debounce } from 'lodash'; const [searchKey, setSearchKey] = useState(''); // 防抖函数 const debounceList = debounce(getList, 500);[/code] [code]<Input value={searchKey} onChange={(e) => { setSearchKey(e.target.value); }} className={`${style.search}`} placeholder="请输入关键词" />[/code]

页面上有一个搜索框,searchKey是通过useState界说的响应式数据,onChange变乱调用了setSearchKey方法,那么只要输入变革时,组件就会重新渲染从而重新生成新的防抖函数debounceList。最终造成防抖功能失效。

二、解决办法

使用 useRef 界说searchKey数据,使其成为非响应式数据,通过 searchKey.current 获取和修改值:

[code]// 搜索关键字 const searchKey = useRef(''); // 修改数据 const setSearchKey = (val) => { searchKey.current = val; };[/code] [code]<Input onChange={(e) => { setSearchKey(e.target.value); }} className={`${style.search}`} placeholder="请输入关键词" />[/code]

三、拓展

关于处置惩罚防抖失效的问题,大概有人会想到使用 useCallback 来缓存 debounce 防抖函数,比如你大概会如许写:

[code]const [searchKey, setSearchKey] = useState(''); const debounceList = useCallback(debounce(getList, 500), []);[/code]

如许防抖功能固然生效了,但是你无法获取最新的searchKey值;如果想获取最新的searchKey值,就要把searchKey加到背面的 [ ] 中,但是如许防抖又失效了。以是只能采用useRef 界说非响应式数据来解决。

到此这篇关于react组件中debounce防抖功能失效的文章就先容到这了,更多相关react组件debounce防抖内容请搜索脚本之家从前的文章或继续欣赏下面的相关文章希望大家以后多多支持脚本之家!


来源:https://www.jb51.net/javascript/3286446zk.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
关闭

站长推荐上一条 /6 下一条

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-7-2 09:22 , Processed in 0.027989 second(s), 18 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

返回顶部