实现简易的函数防抖debounce

780 阅读1分钟
import React, { Component } from 'react';
import { Input, Card, Button } from 'antd';
import { fetchData } from '@/servers/my';

const debounce = (method, wait) => {
 	let timeout
	// args为返回函数调用时传入的参数,传给method
	const debounced = (...args) => {
		const context = this
		if (timeout) {
  			clearTimeout(timeout)
		}
		timeout = setTimeout(() => {
  		// args是一个数组,所以使用fn.apply
  		// 也可写作method.call(context, ...args)
 	 	method.apply(context, args)
		}, wait)
	  }
	return debounced
}

class MyPage extends Component {
	state = {
 		value: '',
	};


	handleInputChange = (e) => {
		this.setState({
  			value: e.target.value,
		});
	};

	render() {
		const { value } = this.state;
		return (
  			<Card>
    			<Input onChange={this.handleInputChange} />
    			<Button style={{ color: 'red' }} onClick={debounce(() => {
      				console.log(value)
    				}, 1000)
    			}
    			>
     			 请求
    			</Button>
  			</Card>
	  );
	}
  }

export default MyPage;

点击一次的效果图

可以看到代码运行消耗了2毫秒的时间