今天做react項目中,給一個 input onKeyDown 事件做節流,出現了節流效果失效。
問題代碼:
1
2
3
4
5
6
7
|
render() { return ( <div className= "search-bar" > <input className= "search-input" type= "text" placeholder= "請輸入要搜索的用戶名(英文)" onKeyDown={ this .throttle( this .handleKeyDown)}/> </div> ) } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
throttle = (fn) => { let valid = true const context = this return function () { if (!valid) return valid = false const args = arguments fn.apply(context, args) setTimeout(() => { valid = true }, 1000); } } handleKeyDown = (e) => { let { value } = e.target const keyCode = e.keyCode if (keyCode !== 13) return if (!value.trim()) return // 發送搜索 this .props.search(value) } |
此處問題出現在:
handleKeyDown() 方法里的 this.props.search(value)
刷新了組件 props,觸發了 react 更新流生命周期。 重新執行了 render();
這樣 throttle() 方法就會重新執行;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
throttle = (fn) => { console.log( '%c throttle初始化' , 'color: red' ); let valid = true const context = this return function () { if (!valid) return valid = false const args = arguments fn.apply(context, args) setTimeout(() => { valid = true }, 1000); } } |
在代碼中加入打印,就會在控制臺看到 throttle初始化 打印多條;
解決方式1:
把節流初始化的位置放到 事件函數賦值
1
2
3
4
5
6
7
|
render() { return ( <div className= "search-bar" > <input className= "search-input" type= "text" placeholder= "請輸入要搜索的用戶名(英文)" onKeyDown={ this .handleKeyDown}/> </div> ) } |
1
2
3
4
5
6
7
8
9
10
11
|
handleKeyDown = this .throttle((e) => { let { value } = e.target const keyCode = e.keyCode if (keyCode !== 13) return if (!value.trim()) return // 發送搜索 this .props.search(value) }) |
解決方式2: 在構造函數中賦值初始化
1
2
3
4
5
6
7
|
render() { return ( <div className= "search-bar" > <input className= "search-input" type= "text" placeholder= "請輸入要搜索的用戶名(英文)" onKeyDown={ this .handleKeyDown}/> </div> ) } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
constructor(props) { super (props) this .handleKeyDown = this .throttle( this .handleSearch) } handleSearch = (e) => { let { value } = e.target const keyCode = e.keyCode if (keyCode !== 13) return if (!value.trim()) return // 發送搜索 this .props.search(value) } |
采坑總結:
要更加深了解 react 生命周期的觸發機制
以上就是React事件節流效果失效的原因及解決的詳細內容,更多關于React事件節流效果失效的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/cleves/p/14663672.html