今日在工作中遇到项目卡顿,导致按钮多次点击后多次提交的问题,于是想着为按钮加个节流,但是在使用时发现和在js中使用不太一样,摸索出来其使用方法,这里简单记录下,等后续有时间再去深入了解其原理。
1.使用自己写的节流函数
import React, { useState } from "react";
import { Button } from "antd";
export default function index() {
const [pre, setPre] = useState(0);
// 节流函数
const throttle =
(fn, delay) =>
(...rest) => {
const current = Date.now();
if (current - pre > delay) {
fn(rest);
setPre(current);
}
};
// 对按钮点击事件包装一层节流
const click_handle = () => {
throttle(click, 2000)();
};
// 点击事件真正的逻辑写这里
const click = () => {
console.log("点击");
};
return (
<div>
<Button onClick={click_handle}>点击</Button>
</div>
);
}
2.使用lodash库中的方法throttle
在函数组件中使用
import React from "react";
import { Button } from "antd";
import throttle from "lodash/throttle"; //引入lodash中的节流函数
export default function index() {
// 对按钮点击事件包装一层节流
const click_handle = throttle(() => click(), 2000);
// 点击事件真正的逻辑写这里
const click = () => {
console.log("点击");
};
return (
<div>
<Button onClick={click_handle}>点击</Button>
</div>
);
}
在类组件中使用
import React, { Component } from "react";
import throttle from "lodash/throttle";
import { Button } from "antd";
export default class index extends Component {
// 对按钮点击事件包装一层节流
click_handle = throttle(() => this.click(), 2000);
// 点击事件真正的逻辑写这里
click = () => {
console.log("点击");
};
render() {
return (
<div>
<Button onClick={this.click_handle}>点击</Button>
</div>
);
}
}
在类组件中还有一种使用方式
import React, { Component } from "react";
import throttle from "lodash/throttle";
import { Button } from "antd";
export default class index extends Component {
constructor(props) {
super(props);
this.click_handle = throttle(this.click_handle, 2000);
}
// 点击事件真正的逻辑写这里
click_handle = () => {
console.log("点击");
};
render() {
return (
<div>
<Button onClick={this.click_handle}>点击</Button>
</div>
);
}
}