react中使用lodash的debounce,使用如下:
//npm i --save lodash
//import debounce from "lodash/debounce";
constructor(props: Props) {
super(props);
this.state = {
value: "",
};
this.handleChange = this.handleChange.bind(this);
this.debounceInput = debounce(this.debounceInput, 500);
//this.debounceInput = debounce(this.debounceInput.bind(this), 500);
}
handleChange(e: any) {
this.setState({
value: e.target.value,
});
this.debounceInput(e.target.value);
}
debounceInput(value: any) {
console.log(value);
}
render() {
return <Input value={this.state.value} onChange={this.handleChange} />;
}
The debounced function ensures that:
- API calls will be debounced
- the debounced function always returns a promise
- only the last call's returned promise will resolve
- a single
this.setState({ result });
will happen per API call
The important part here is to create a single debounced (or throttled) function per component instance. You don't want to recreate the debounce (or throttle) function everytime, and you don't want either multiple instances to share the same debounced function.
所以下面写法有问题:
componentDidMount() {
document.addEventListener('keydown', _.debounce(this.handleKeydown))
}
componentWillUnmount() {
document.removeEventListener('keydown', .debounce(this.handleKeydown))
}
改为如下:
constructor(props){
super(props)
this.handleKeydown= _.debounce(this.handleKeydown, 100)
}
componentDidMount() {
document.addEventListener('keydown', this.handleKeydown)
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeydown)
}