在react中使用防抖函数时,发现并不能生效,直接看代码
类组件
import React from "react";
import debounce from "lodash/debounce";
export default class Test extends React.Component {
handleOnEmit = () => {
console.log("点击了");
};
handleOnClick = () => {
debounce(this.handleOnEmit, 1000);
};
render() {
return <button onClick={this.handleOnClick}>连续点击,查看执行情况</button>;
}
}
这是因为每次点击就会生成新的debounce函数,比如点击10次就会生成10个debounce函数,因此会触发10次;因此我们需要将handleOnEmit在构造函数中定义好 避免重复创建;或者直接写在render中
import React from "react";
import debounce from "lodash/debounce";
export default class Test extends React.Component {
constructor(props) {
super(props);
this.handleOnClick = debounce(this.handleOnEmit, 200);
}
handleOnEmit = () => {
console.log("点击了");
};
render() {
return <button onClick={this.handleOnClick}>连续点击,查看执行情况</button>;
}
}
或者
import React from "react";
import debounce from "lodash/debounce";
export default class Test extends React.Component {
handleOnEmit = () => {
console.log("点击了");
};
render() {
return (
<button onClick={debounce(this.handleOnEmit, 200)}>
连续点击,查看执行情况
</button>
);
}
}
函数组件
同样 如果在函数组件中也会有问题 我们需要用useCallback、useRef、或者直接使用
const Test = () => {
const handleOnEmit = () => {
console.log("点击了");
};
return (
<button onClick={debounce(handleOnEmit, 200)}>
连续点击,查看执行情况
</button>
);
};
const Test = () => {
const handleOnEmit = (e: any) => {
console.log("点击了", e);
};
const handleOnClick = useCallback(
debounce((e) => handleOnEmit(e), 200),
[],
);
return <button onClick={handleOnClick}>连续点击,查看执行情况</button>;
};
const Test = () => {
const handleOnEmit = (e: any) => {
console.log("点击了", e);
};
const handleOnClick = useRef(debounce((e) => handleOnEmit(e), 200)).current;
return <button onClick={handleOnClick}>连续点击,查看执行情况</button>;
};