最近功能需求,在用户输入的一个输入框后,500毫秒触发事件,解决方案很简单,setTimeout嘛......函数
代码以下:this
class A extends React.Component{ handleChange(target){ var that = this; if(this.timer){ clearTimeout(this.timer); } this.timer = setTimeout(setTimeoutFun(that,target),500); } setTimeoutFun(_self,_target){ _self.setState({ xxx:_target.value }); _self.timer = null; } render(){ return( <input onChange={this.handleChange} xxxxxx /> ) } }
看似合情合理,可是呢,彻底很差用,不是别的很差用,并且彻底不会clear,并且每一个setTimeout都执行了,这是啥缘由呢?想了一想,因而又改了一个写法:code
class A extends React.Component{ handleChange(target){ var that = this; if(this.timer){ clearTimeout(this.timer); } this.timer = setTimeout(()=>{ that.setState({ xxx:target.value }); },500); } render(){ return( <input onChange={this.handleChange} xxxxxx /> ) } }
Bingo!!好用了,setInterval也是一样的道理,别忘记clear就好。事件
可是为何匿名函数就能够,可是在建立的模块中定义的方法就很差用呢?这个缘由还在研究,等研究明白了再更新,但愿能对你们有帮助!!get