【问题标题】:ComponentWillUnmount() doesn't clear intervalComponentWillUnmount() 不清除间隔
【发布时间】:2019-06-21 05:24:40
【问题描述】:

我有一个倒计时计时器,当它变为 0 时应该调用一个方法。然后,呈现一个新页面,倒计时应该重置并重新开始。它按预期工作,直到组件卸载。 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;

我怀疑它在某处会导致无限循环。我认为清除componentWillUnmount() 中的间隔会起作用,但显然有一个错误。即使组件被卸载并且我不知道如何停止它,似乎也有一个间隔运行。

【问题讨论】:

  • 我没有看到 this.timerFunction 是在哪里定义的,除了在 decrement 的函数体中,并且因为 decrement 没有被声明为 lambda,所以它有自己的 this 范围。我猜那是你的问题。如果 decrement 被声明为 decrementTimeRemaining,它可能会起作用,因为 this.timerFunction 将绑定到 Countdown 类的范围。
  • 很遗憾没有解决。
  • 您应该将 this.state.timer 重置为默认值,而不是在计时器函数中调用 decrement()。在计时器函数中调用 decrement() 至少是一种竞争条件。
  • 您能否编辑您的问题以包含所有相关代码 sn-ps?如果您不向我们展示正在传入的函数和道具,我们无法知道问题出在哪里。
  • 嗨!或许你可以在这里找到答案 stackoverflow.com/questions/43508744/…

标签: javascript reactjs


【解决方案1】:

我认为您的 decrementTimeRemaining 函数过于复杂。我会像这样重构函数:

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

现在componentWillUnmount是唯一调用clearInterval的地方,componentDidMount是唯一开始间隔的地方。

【讨论】:

  • 谢谢,你就是那个人!我想我明白了,您无需清除间隔,只需让它以新值滚动即可。我想我必须清除间隔并在它达到零时开始一个新的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多