React事件节流效果失效的原因及解决
今天做react项目中,给一个 input onKeyDown 事件做节流,出现了节流效果失效。
问题代码:
render() {
return (
<div className="search-bar">
<input className="search-input" type="text" placeholder="请输入要搜索的用户名(英文)" onKeyDown={this.throttle(this.handleKeyDown)}/>
</div>
)
}
throttle = (fn) => {
let valid = true
const context = this
return function() {
if (!valid) return
valid = false
const args = arguments
fn.apply(context, args)
setTimeout(() => {
valid = true
}, 1000);
}
}
handleKeyDown = (e) => {
let { value } = e.target
const keyCode = e.keyCode
if (keyCode !== 13) return
if (!value.trim()) return
// 发送搜索
this.props.search(value)
}
此处问题出现在:
handleKeyDown() 方法里的 this.props.search(value)
刷新了组件 props,触发了 react 更新流生命周期。 重新执行了 render();

这样 throttle() 方法就会重新执行;
throttle = (fn) => {
console.log('%c throttle初始化', 'color: red');
let valid = true
const context = this
return function() {
if (!valid) return
valid = false
const args = arguments
fn.apply(context, args)
setTimeout(() => {
valid = true
}, 1000);
}
}
在代码中加入打印,就会在控制台看到 throttle初始化 打印多条;
解决方式1:
把节流初始化的位置放到 事件函数赋值
render() {
return (
<div className="search-bar">
<input className="search-input" type="text" placeholder="请输入要搜索的用户名(英文)" onKeyDown={this.handleKeyDown}/>
</div>
)
}
handleKeyDown = this.throttle((e) => {
let { value } = e.target
const keyCode = e.keyCode
if (keyCode !== 13) return
if (!value.trim()) return
// 发送搜索
this.props.search(value)
})
解决方式2: 在构造函数中赋值初始化
render() {
return (
<div className="search-bar">
<input className="search-input" type="text" placeholder="请输入要搜索的用户名(英文)" onKeyDown={this.handleKeyDown}/>
</div>
)
}
constructor(props) {
super(props)
this.handleKeyDown = this.throttle(this.handleSearch)
}
handleSearch = (e) => {
let { value } = e.target
const keyCode = e.keyCode
if (keyCode !== 13) return
if (!value.trim()) return
// 发送搜索
this.props.search(value)
}
采坑总结:
要更加深了解 react 生命周期的触发机制
以上就是React事件节流效果失效的原因及解决的详细内容,更多关于React事件节流效果失效的资料请关注脚本之家其它相关文章!
相关文章
详解在create-react-app使用less与antd按需加载
这篇文章主要介绍了详解在create-react-app使用less与antd按需加载,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-12-12
React Hooks中 useRef和useImperativeHandle的使用方式
这篇文章主要介绍了React Hooks中 useRef和useImperativeHandle的使用方式,文中说明了useRef和useCallback一起使用, 可以解决闭包陷阱的问题,本文结合实例代码介绍的非常详细,需要的朋友可以参考下2023-10-10
react + vite + ts项目中优雅使用.svg文件
这篇文章主要为大家介绍了react + vite + ts项目中优雅使用.svg文件,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-08-08


最新评论