首页 > 解决方案 > 递减计数器有奇怪的行为

问题描述

我正在用 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>

标签: javascriptreact-native

解决方案


您正在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)
    }


推荐阅读