繁体   English   中英

递减计数器具有奇怪的行为

[英]Decreasing counter has bizarre behaviour

我正在用setInterval构建一个计数器,该计数器每秒减少一次时间,在前几秒钟工作,然后陷入困境,并同时增加和减少。

在我的情况下,我从5:00(m:ss)开始,几秒钟后围绕4:49环绕,然后开始增加然后减少...

不知道发生了什么。

start = () => {
        console.log('starting')
        let timeLeft = this.state.totalDuration
        setInterval(() => {
            if (timeLeft > 0) {
                timeLeft = (timeLeft - 1000)
                this.setState({ totalDuration: timeLeft })
            }
        }, 1000)
    }



 render() {

        return (
            <View style={styles.container}>
                <Timer interval={this.state.totalDuration}></Timer>
                <ButtonsRow>
                    <RoundButton title='Reset' color='white' background='grey'></RoundButton>
                    <RoundButton onPress={this.start()} title='Start' color='white' background='red'></RoundButton>
                </ButtonsRow>
</View>

您正在时间间隔函数外部的闭包中捕获timeLeft变量。 因此,当按下开始键时,它将被捕获一次,之后将保持相同的值。 而是使用接受回调的setState变体。

start = () => {
        console.log('starting')
        const interval = setInterval(() => {
             this.setState(state => { 
                  if (state.totalDuration > 0) 
                    return { totalDuration : state.totalDuration - 1000 }
                  else {
                    clearInterval(interval)
                    return {}
                  }
              })
        }, 1000)
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM