gpt4 book ai didi

javascript - 如何清除在组件生命周期中创建的 setTimeout?

转载 作者:行者123 更新时间:2023-11-28 17:07:53 27 4
gpt4 key购买 nike

问题是我收到了这个警告:

Warning: Can’t call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

正是因为这个:

  componentDidUpdate(props, state) {
const {
pushNotificationData,
unassignedPickUpPassengers,
unassignedDropOffPassengers,
} = this.props;

if (props.pushNotificationData !== pushNotificationData) {
this.applyOpacityForSomeSeconds(0.5, 0);
}

if (
props.unassignedPickUpPassengers !== unassignedPickUpPassengers ||
props.unassignedDropOffPassengers !== unassignedDropOffPassengers
) {
this.applyOpacityForSomeSeconds(1, 1000);
}
}

applyOpacityForSomeSeconds = (setOpacity, timeout) =>
setTimeout(() => {
this.setState({ lastIndexOpacity: setOpacity });
}, timeout);

我应该如何清除 componentWillUnmount 上的超时?这是这样做的正确方法还是还有其他方法?

最佳答案

您需要保留它的引用,如下所示:

applyOpacityForSomeSeconds = (setOpacity, timeout) =>
clearTimeout(this.timeout) // notice that you don't have to check if this.timeout is null or undefined just let clearTimeout handle it

this.timeout = setTimeout(() => {
this.setState({ lastIndexOpacity: setOpacity });
}, timeout);

注意,该引用设置为 this.timeout = setTimeout(...)。您可以在构造函数中或其他位置使用 null 初始化该引用 - I对此总是犹豫不决。:)

如果需要,您可以将 clearTimeout(this.timeout) 移动或复制到 componentWillUnmount 中。

关于javascript - 如何清除在组件生命周期中创建的 setTimeout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55290458/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com