React中的setTimeout、setInterval的注意事項

最近功能需求,在用戶輸入的一個輸入框後,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

相關文章
相關標籤/搜索