class类组件 防抖的使用
import React, { Component } from 'react'
import {debounce} from 'lodash'
import { Button } from 'antd'
export default class TestClass extends Component {
state = {
value:0
}
dbclick = ()=> {
if(this.time) clearTimeout(this.time)
this.time = setTimeout(this.handlerClick,500)
}
handlerClick = ()=>{
const newvalue= this.state.value+1
this.setState({value:newvalue})
clearTimeout(this.time)
}
debounceClick = ()=>{
if(!this.mydebounce){
this.mydebounce = debounce(this.add,500)
}
this.mydebounce()
}
add = ()=>{
const newvalue= this.state.value+1
this.setState({value:newvalue})
}
render() {
return (
<div>
{this.state.value}
<Button type="primary" onClick={this.dbclick}>原生 click</Button>
<br/>
<Button type="primary" onClick={this.debounceClick}>lodash click</Button>
</div>
)
}
}
函数组件防抖的使用
import React, { useCallback, useEffect, useState } from "react";
import { debounce } from "lodash";
export default function App() {
const [value, setValue] = useState(0);
const dbclick = ()=>{
const click =debounce(() => setValue(value + 1), 500)
click()
}
return <button onClick={()=>{
dbclick()
}}>{value}</button>;
}