如何在React搜索的onSearchChanged方法中集成debounce防抖功能
你当前的写法问题在于:接口请求逻辑直接放在了onSearchChanged的setState回调中,每次输入都会立刻触发请求,你定义的debouncedTerm仅执行了日志打印,没有起到限制请求频率的作用。正确的集成方式是把需要防抖的接口请求逻辑全部放到防抖函数的回调中,输入框的实时状态更新不需要防抖,避免输入字符延迟显示。
修改方案
1. 重新定义防抖函数封装请求逻辑
你不需要修改已有的debounce工具函数,只需要把原onSearchChanged里的请求逻辑,放到防抖函数的回调中:
debounce = (callback, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => callback(...args), delay); } } // 封装防抖的搜索请求,替换原来的debouncedTerm debouncedSearch = this.debounce((searchTerm) => { let newData = {...this.state}; if(typeof this.props.source !== "undefined"){ newData.source = this.props.source } newData.params = { searchBar : searchTerm } Api.fetchQuestions(newData.params) .catch( error => { if (typeof error.message !== "undefined"){ newData.config.formMessage = { message : error.message, success : false, } newData.widgetStatus = false; this.setState(newData) } return {data:{data:[]}} }) .then( response => { if(response.data.status === 'success'){ this.setState({ questions: [...response.data.questions.items], loading: false }); } }) }, 300);
2. 简化onSearchChanged逻辑
onSearchChanged仅负责更新输入框的实时显示状态,同时调用上面定义的防抖请求方法即可:
onSearchChanged = data => { const searchBar = data.target.value.toLowerCase(); // 实时更新输入框状态,保证输入体验正常 this.setState({ searchBar: searchBar, loading: true // 可选:增加搜索中状态提示 }); // 触发防抖搜索 this.debouncedSearch(searchBar); };
注意事项
- 防抖实例必须挂载到类实例上,不要在
render、onSearchChanged内部创建,否则每次触发事件都会生成新的防抖函数,内置的计时器会被重置,防抖失效 - 如果组件会卸载,建议增加清理逻辑避免内存泄漏,可以给
debounce扩展取消方法,在componentWillUnmount中调用清除计时器
内容的提问来源于stack exchange,提问作者Elichy
相关产品推荐
相关产品推荐

