简体   繁体   English

ComponentWillUnmount() 不清除间隔

[英]ComponentWillUnmount() doesn't clear interval

I have a countdown timer that should invoke a method once it turns to 0. Then, a new page is rendered and the countdown should reset and start again.我有一个倒数计时器,一旦它变成 0 就应该调用一个方法。然后,呈现一个新页面,倒计时应该重置并重新开始。 It works as intended until the component unmounts.它按预期工作,直到组件卸载。 The method timeNext() gets then called every second because the interval doesn't stop anymore.然后每秒调用timeNext()方法,因为间隔不再停止。

import React, { Component } from 'react';

class Countdown extends Component {

    state = {
        timer: this.props.timer
    }

    decrementTimeRemaining = () => {
        if (this.state.timer > 0) {
            this.setState({
                timer: this.state.timer - 1
            });
        } else {
            clearInterval(this.timerFunction);

            this.props.timeNext();
            this.setState({ timer: this.props.timer });
            this.decrement();
        }
    };

    decrement() {
        this.timerFunction = setInterval(() => {
            this.decrementTimeRemaining();
        }, 1000);
    }

    componentDidMount() {
        this.decrement()
    }

    componentWillUnmount() {
        console.log("unmounted")
        clearInterval(this.timerFunction);
    }

    render() {
        return (
            <div>{this.state.timer} </div>
        )
    }
}

export default Countdown;

I suspect it somewhere causes an infinite loop.我怀疑它在某个地方会导致无限循环。 I thought clearing the interval in componentWillUnmount() would work, but apparently there is a mistake.我认为清除componentWillUnmount()的间隔会起作用,但显然有一个错误。 There seems to be an interval running even when the component gets unmounted and I don't know how to stop it.即使组件被卸载,似乎也有一个运行间隔,我不知道如何停止它。

I think you've over-complicated your decrementTimeRemaining function.我认为您的 decrementTimeRemaining 函数过于复杂。 I would refactor the function like this:我会像这样重构函数:

decrementTimeRemaining = () => {
    if (this.state.timer > 0) {
        this.setState({
            timer: this.state.timer - 1
        });
    } else {
        this.setState({ timer: this.props.timer });
    }
};

Now componentWillUnmount is the only place that clearInterval is called and componentDidMount is the only place that the interval is started.现在 componentWillUnmount 是唯一调用 clearInterval 的地方,并且 componentDidMount 是唯一开始间隔的地方。

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

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