import { debounce } from '@/utils/utils';
<Button
style={{ marginLeft: 10 }}
onClick={debounce(() => {
const url = DownloadTasks?.DOWNLOADTASKS?.clientexporttask?.url;
dispatch({
type: `${DownloadTasks.EXPORTTASKMODEL}`,
payload: { listParams, url },
});
}, 2000)}
>
导出表格
</Button>
// 防抖
export const debounce = (fn = () => {}, wait = 1000) => {
let timeout;
return res => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => fn(res), wait);
};
};
对第一次做优化
// 防抖
export const debounce = (fn = () => {}, wait = 1000, triggle = false) => {
let timeout;
return res => {
if (timeout) {
clearTimeout(timeout);
}
if (triggle) {
// 这里如果是真值 就把把点击的第一次实现
const firstClick = !timeout;
if (firstClick) {
fn(res);
}
timeout = setTimeout(() => {
timeout = null;
}, wait);
} else {
timeout = setTimeout(() => fn(res), wait);
}
};
};
进一步优化
抽出按钮作为公共组件
每次点击可以配置置灰操作,也可以配置为防抖处理
import React, { useState } from 'react';
import { Button } from 'antd';
import Authorized from '@/utils/Authorized';
import DownloadTasks from '@/services/DownloadTasks';
import { debounce } from '@/utils/utils';
import { useDispatch } from 'react-redux';
export default ({ authority, listParams = {}, type = '', name = '导出表格' }) => {
const dispatch = useDispatch();
const [exportAbled, setExportAbled] = useState(false);
return (
<Authorized authority={[authority]} noMatch={null}>
<Button
disabled={exportAbled}
onClick={debounce(
() => {
const url = DownloadTasks?.DOWNLOADTASKS[type]?.url;
dispatch({
type: `${DownloadTasks.EXPORTTASKMODEL}`,
payload: { listParams, url },
});
setExportAbled(true);
setTimeout(() => {
setExportAbled(false);
}, 2000);
},
2000,
true,
)}
style={{ marginLeft: 10 }}
>
{name}
</Button>
</Authorized>
);
};