2017-03-07 56 views
4

當前組件有state.breaker值爲false。當滾動事件被捕獲時,它看起來在state,如果它的false它做了一些東西。反應。 this.setState不是setTimeout裏面的函數

我想有某種行動之前靜態的延遲會復發,這就是爲什麼裏面goTo功能state.breaker設置爲true,並阻止當前方法的進一步的邏輯下一個2s直到setTimeout將返回到false

但在當前時刻出現以下錯誤遺漏的類型錯誤:this.setState不是一個函數setState被稱爲內setTimeout

class Slide extends Component { 
    constructor(props) { 
    super(props) 

    this.state = { 
     breaker: false 
    } 

    this.scrollRedirect = this.scrollRedirect.bind(this); 
    } 

    componentDidMount() { 
    this.refs.holder.addEventListener('mousewheel', this.scrollRedirect); 
    } 


    scrollRedirect(e) { 

    const path = this.props.location.pathname, 
    goTo = (route) => { 
     this.setState({breaker: true}); 
     hashHistory.push(route); 

     setTimeout(function() { 
     this.setState({breaker: false}); 
     }, 2000) 
    }; 

    if (!this.state.breaker) { 
     ... code that executes goTo on condition 
    } 
    } 

    ... render code 

} 

回答

23

您正在失去背景。使用箭頭功能簡單的方式來保持適當的執行上下文:

setTimeout(() => { 
    this.setState({breaker: false}); 
}, 2000) 

請記住,匿名函數將有背景window內,除非你明確地Function.prototype.bind綁定。所以這裏是解決這個問題的另一種方法:

setTimeout(function() { 
    this.setState({breaker: false}); 
}.bind(this), 2000) 
+0

是真的,謝謝! :) – volna