在 React 组件中使用定时器时,为了防止内存泄漏,必须在组件卸载时清除定时器。componentWillUnmount 生命周期方法是清除定时器的最佳时机。

以下是一个示例代码,展示了如何在 componentWillUnmount 中清除两个定时器: _timer_interTimer

return t = l, (n = [{
    key: 'componentDidMount',
    value: function() {
        var e = this;
        this.startCount();
        var t = 0
          , n = this.props.voiceOffset;
        this._interTimer = setInterval(function() {
            ++t >= n ? (0, u.setAward)({ voiceCodeVisible: !0 }) : clearInterval(e._interTimer)
        }, 1e3);
    }
}, {
    key: 'componentWillUnmount',
    value: function() {
        clearTimeout(this._timer);
        clearInterval(this._interTimer);
    }
}, {
    key: 'startCount',
    value: function() {
        var e = this
          , t = this.props
          , n = t.totalTime
          , r = t.onCount;
        'function' == typeof r && r(),
        function t(n) {
            n <= 0 ? e.setState({ text: '重新发送', waiting: !1 }) : (e.setState({ text: n + 's后再次发送', waiting: !0 }), e._timer = setTimeout(function() {
                t(n - 1)
            }, 1e3))
        }(n)
    }
}]), t;

解释:

  • _timer 是在 startCount 方法中设置的。
  • _interTimer 是在 componentDidMount 方法中设置的。
  • componentWillUnmount 方法中,使用 clearTimeout(this._timer) 清除 _timer,使用 clearInterval(this._interTimer) 清除 _interTimer

总结:

始终在 componentWillUnmount 生命周期方法中清除定时器,可以有效地防止内存泄漏,确保组件的正确卸载。

React 组件生命周期中清除定时器最佳实践

原文地址: https://www.cveoy.top/t/topic/lHHb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录