参考文章:
https://blog.csdn.net/wangweiscsdn/article/details/107844516
https://blog.csdn.net/weixin_47958188/article/details/107231598
1. lodash防抖
需要下载loadsh依赖:
# yarn add lodash
npm i lodash
引入:
// lodash 支持按需加载,有利于打包结果优化
import debounce from 'lodash/debounce';
// 不建议下面这样使用,因为这样会加载整个模块。
import _ from 'lodash'
_.debounce()
核心代码:
/**
* @description: 防抖
* @param {*} debounce
* @return {*}
*/
const debounceSubmit = debounce(() => {
form.submit();
}, 300);
完整代码:
import React, { useState } from 'react';
import { Row, Col, Form, Input, } from 'antd';
import debounce from 'lodash/debounce';
type ITestFilterProps = {
store: any;
};
const TestFilter: React.FC<ITestFilterProps> = ({ store }) => {
const [form] = Form.useForm();
const handleFilterFinish = (values: any) => {
console.log(values, 'values----')
//接口
};
/**
* @description: 防抖
* @param {*} debounce
* @return {*}
*/
const debounceSubmit = debounce(() => {
form.submit();
}, 300);
return (
<Row>
<Col span= { 18} >
<Form layout="inline" form = { form } onFinish = { handleFilterFinish } >
<Form.Item name="name" >
<Input
placeholder="名称搜索"
onChange = { debounceSubmit }
allowClear = { true}
/>
</Form.Item>
< /Form>
< /Col>
< /Row>
);
};
export default TestFilter;
2. React hooks自定义防抖
核心代码:
// 防抖函数
function useDebounce(fn, delay) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, [fn]);
return useCallback(function f(...args) {
if (current.timer) {
clearTimeout(current.timer);
}
current.timer = setTimeout(() => {
current.fn.call(this, ...args);
}, delay);
})
}
const handleValue = useDebounce(v => { // 获取input的值
const value = v.target.value
console.log({ value })
form.submit();
}, 800)
完整代码:
import React, { useEffect, useCallback, useRef } from 'react';
import { Row, Col, Form, Input } from 'antd';
import debounce from 'lodash/debounce';
type ITestFilterProps = {
store: any;
};
const TestFilter: React.FC<ITestFilterProps> = ({ store }) => {
const [form] = Form.useForm();
const handleFilterFinish = (values: any) => {
console.log(values, 'values----')
//接口
};
// 防抖函数
function useDebounce(fn, delay) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, [fn]);
return useCallback(function f(...args) {
if (current.timer) {
clearTimeout(current.timer);
}
current.timer = setTimeout(() => {
current.fn.call(this, ...args);
}, delay);
})
}
const handleValue = useDebounce(v => { // 获取input的值
const value = v.target.value
console.log({ value })
form.submit();
}, 800)
return (
<Row>
<Col span= { 18} >
<Form layout="inline" form = { form } onFinish = { handleFilterFinish } >
<Form.Item name="name" >
<Input
placeholder="名称搜索"
allowClear = { true}
onChange = { v => handleValue(v)}
/>
< /Form.Item>
< /Form>
< /Col>
< /Row>
);
};
export default TestFilter;