2017-09-03 92 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是异步的,因此确保它访问正确的状态。