如果满足条件,您可以清除setInterval吗?不使用componentDidMount吗?

问题描述 投票:0回答:1

我正在创建一个简单的计时器。我希望计时器在到达00秒时重置。我正在使用setInterval,但在this.state.seconds中每次都不清除值为0。我已经看过一些使用componentDidMount和componentDidUnmount的解决方案,但会对从调用setInterval本身的方法执行和清除setInterval感兴趣。这有可能吗?

直到现在,计时器仍会在0秒后继续减少。这是我的代码笔草稿:https://codepen.io/tonytony92/pen/bGdJeRg

class MyApp extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            minutes: 25,
            seconds: 59,
            play: false,
            display: "SESSION"
        }
        this.handlePlay = this.handlePlay.bind(this)
    }


    handlePlay() {
        let func1 = () => {
            this.setState({
                seconds: this.state.seconds - 1
            })
            console.log(this.state.seconds)
        }

        if (this.state.seconds > 0) {
            this.Myvar = setInterval(() => {
                console.log(this.state.seconds)
                this.setState({
                    seconds: this.state.seconds - 1
                })
            }, 200)
        }
        else {
            console.log("minus")
            clearInterval(this.Myvar)  /// not clearing ///
        }
    }
}
javascript reactjs react-redux this
1个回答
1
投票

handlePlay会在单击按钮时启动计时器,但bu不会像您期望的那样检查剩余时间。

这是因为提供给setInterval的功能是

console.log(this.state.seconds)
this.setState({
  seconds: this.state.seconds - 1
})

而不是功能handlePlay

为了获得更好的可读性和可维护性(并使代码工作),请从启动计时器的代码中拆分处理时间减少的逻辑。像这样:

class MyApp extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            minutes: 0,
            seconds: 10,
            play: false,
            display: "SESSION"
        }
        this.handlePlay = this.handlePlay.bind(this);
        this.handleTime = this.handleTime.bind(this);
    }

    // handlePlay only launches the timer.
    handlePlay() {
        this.Myvar = setInterval(this.handleTime, 200);
    }

    // handleTime deals with the logic of decrementing time.
    handleTime() {
        if (this.state.seconds > 0) {
            console.log(this.state.seconds)
            this.setState({
                seconds: this.state.seconds - 1
            })
        } else {
            console.log("minus")
            clearInterval(this.Myvar)
        }
    }
}

handlePlay现在是UI(单击按钮)和逻辑(减少处理时间)之间的接口。它仅使用setInterval启动计时器。

handleTime处理时间减少的逻辑。每当setInterval触发并在时间结束后停止计时器时,就会调用该方法。

© www.soinside.com 2019 - 2024. All rights reserved.