Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 递减计数器有奇怪的行为_Javascript_React Native - Fatal编程技术网

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

Javascript 递减计数器有奇怪的行为,javascript,react-native,Javascript,React Native,我正在用setInterval构建一个计数器,它每秒钟减少一次时间,在前几秒钟工作,然后卡住,同时增加和减少 在我的例子中,我从5:00(m:ss)开始,几秒钟后,在4:49附近的街区开始增加,然后减少 不知道在搞什么 start = () => { console.log('starting') let timeLeft = this.state.totalDuration setInterval(() => {

我正在用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>
start=()=>{
console.log('starting')
让timeLeft=this.state.totalDuration
设置间隔(()=>{
如果(时间间隔>0){
timeLeft=(timeLeft-1000)
this.setState({totalDuration:timeLeft})
}
}, 1000)
}
render(){
返回(

您正在间隔函数外的闭包中捕获
timeLeft
变量。因此,按下start时捕获一次,之后保持相同的值。请改用接受回调的
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)
    }


这不是您问题的解决方案,但如果
timeLeft
是,您应该
clearInterval