React 實現input輸入框的防抖和節流
1.為什么使用防抖和節流
對於頻繁觸發的事件 比如keydown keyup事件 當頻繁點擊時候 會多次觸發事件 頁面出現卡頓 影響性能
2.函數防抖(debounce):間隔時間內只執行一次 函數節流(throttle):間隔時間內執行
3.使用場景
函數防抖:搜索框等
函數節流:鼠標不斷點擊事件等
4.目的
提升性能 提高用戶體驗
5.用react實現防抖和節流
剛好react腳手架是集成了lodash的
import throttle from 'lodash/throttle';
export default class Search extends Component {
constructor(props) {
super(props)
this.handleSearch = throttle(this.handleSearch, 1000);//這里的間隔就是每xx時間內只執行一次該函數
}
handleSubmit = (e) => {
e.preventDefault();
this.handleSearch();
}
handleSearch = () => {
...
}
render() {
return (
<form onSubmit={this.handleSubmit}><form>
)
}
}