2017-09-03 33 views
2

我正在做一個倒計時器作爲一個React練習(對於我自己,而不是一個類或任何東西),並且一切正常(儘管筆記總是受歡迎),除了我注意到它會繼續計數即使在卸載組件後也是如此。停止組件中的計時器

所以現在我想讓它停止卸載,但似乎無法做到正確。在卸載時停止setInterval的協議是什麼?以下是我的:

class TimerVal extends Component { 
    constructor(props) { 
    super(props) 
    this.state = { 
     timeToGo: 30 
    } 
    } 
    secondsToMMSS(seconds) { 
    //returns "mm:ss" 
    } 
    componentDidMount() { 
    setInterval(
    () => this.setState({ 
     timeToGo: this.state.timeToGo - 1 
     }), 
     1000 
    ) 
    } 
    componentWillUnmount() { 
    () => this.setState({ 
     timeToGo: undefined 
    }) 
    } 
    render() { 
    // styles 
    console.log(this.state) 
    const count = (this.state.timeToGo > 0) ? this.secondsToMMSS(this.state.timeToGo) : "00:00" 
    console.log(count) 
    return(
     <div style={timerStyle}> 
     <span style={timerSpanStyle}> 
      {count} 
     </span> 
     </div> 
    ); 
    } 
} 

回答

3

有幾件事。首先,這沒有做任何事情:

() => this.setState({ 
    timeToGo: undefined 
}) 

你只是定義了一個匿名函數,並且什麼也不做。接下來,不要在倒計時停止時將timeToGo設置爲undefined。間隔將繼續進行。相反,清除間隔:

this.interval = setInterval(
() => this.setState({ 
    timeToGo: this.state.timeToGo - 1 
    }), 
    1000 
) 

然後在componentWillUnmount

clearInterval(this.interval) 

這將清除乾淨倒計時。最後,清除倒數到達0的時間間隔,否則它將繼續運行。這費用資源:

this.interval = setInterval(
() => { 
    if(this.state.timeToGo > 0) { 
     this.setState(prevState => ({ 
     timeToGo: prevState.timeToGo - 1 
     })) 
    } else { 
     clearInterval(this.interval) 
    } 
    }, 
    1000 
) 

這將清除間隔一旦達到0。此外,請注意,我用prevState。由於setState是異步的,因此確保它訪問正確的狀態。