好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

React事件节流效果失效的原因及解决

今天做react项目中,给一个 input onKeyDown 事件做节流,出现了节流效果失效。

问题代码:

?

render() {

     return (

       <div className= "search-bar" >

         <input className= "search-input" type= "text" placeholder= "请输入要搜索的用户名(英文)" onKeyDown={ this .throttle( this .handleKeyDown)}/>

       </div>

     )

   }

?

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() 方法就会重新执行; 

?

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: 

把节流初始化的位置放到 事件函数赋值

?

render() {

     return (

       <div className= "search-bar" >

         <input className= "search-input" type= "text" placeholder= "请输入要搜索的用户名(英文)" onKeyDown={ this .handleKeyDown}/>

       </div>

     )

   }

?

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: 在构造函数中赋值初始化

?

render() {

     return (

       <div className= "search-bar" >

         <input className= "search-input" type= "text" placeholder= "请输入要搜索的用户名(英文)" onKeyDown={ this .handleKeyDown}/>

       </div>

     )

   }

?

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

dy("nrwz");

查看更多关于React事件节流效果失效的原因及解决的详细内容...

  阅读:59次