如何处理以设置间隔卸载组件以避免内存泄漏

问题描述 投票:0回答:1

我有一个React组件,它以倒计时器开始,当按下按钮或倒计时到零时,组件被卸载。它的实现是这样的:

state = {
  counter: 60,
};

componentWillMount() {
  this.doCountDown();
}

doCountDown() {
  if (this.state.counter < 1) {
    return this.props.tryAgain();
  }
  this.setState(prevState => ({ counter: prevState.counter - 1 }));
  setTimeout(() => this.doCountDown(), 1000);
}

这不是Unmounting a Component with a SetInterval in React的副本。

在我的情况下,我有一个递归事件正在进行,所以我不能像所提到的链接中的示例清除间隔。

任何人都有任何想法怎么办?

有关更多解释:this.props.tryAgain()将更高的状态更改,导致此组件卸载。发生这种情况时,由于超时,状态仍会在组件已卸载时尝试更改。这表明内存泄漏并且是不好的做法。所以我试图找到一个好的方法来防止这种情况发生。

reactjs memory-leaks settimeout setinterval setstate
1个回答
1
投票

您需要在卸载时调用clearInterval方法调用:

componentWillUnmount() {
    clearInterval(this.timeout)
}


doCountDown() {
    if (this.state.counter < 1) {
        return this.props.tryAgain();
    }
    this.setState(prevState => ({ counter: prevState.counter - 1 }));
    this.timeout = setTimeout(() => this.doCountDown(), 1000);
}
© www.soinside.com 2019 - 2024. All rights reserved.