在react中使用防抖以及节流函数
这里已防抖函数举例;
debounce.js
export const debounce=(fn, wait=1000)=> {
var timer = null;
return function () {
var context = this
var args = arguments
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
export const throttle = (fn, gapTime=500)=> {
let _lastTime = null;
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn();
_lastTime = _nowTime
}
}
}
在react组件中使用
index.jsx
import React from 'react';
import {debounce} from '@utils/debounce'
class Demo extends React.component{
add=(item)=>{
console.log(item)//想要传的参数'
}
fn=debounce(this.add)
render (){
return <div>
<button onClick={this.fn.bind(null,'想要传的参数')}></button>
<button onClick={()=>this.fn.call(null,'想要传的参数')}></button>
</div>
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state={
test:'我是子组件的返回值'
}
}
add = debounce((t)=>{
console.log('t',t)//t 123123123
return this.state
})
render() {
return (
<div>
<Button onClick={()=>{
this.add('123123123')
}}>我要测试一下</Button>
</div>
);
}
}