gpt4 book ai didi

reactjs - 取消订阅 rxjs 中的计时器

转载 作者:行者123 更新时间:2023-12-04 15:37:43 27 4
gpt4 key购买 nike

嗨,我有一个正在运行的计时器,它应该在每 10 秒后显示一个组件 30 秒。我的代码是这样的`

import { timer } from "rxjs";

componentWillReceiveProps(nextProps, nextState) {
console.log("RECEIVED PROPS");
if (this.props.venuesBonusOfferDuration === 0) {
this.subscribe.unsubscribe();
}

this.firstTimerSubscription;
this.secondTimerSubscription;
// if (this.state.isMounted) {
if (
nextProps.showBonusObj &&
(!nextProps.exitVenue.exitVenueSuccess || nextProps.enterVenues)
) {
// console.log("isMounted" + this.state.isMounted);

//if (this.state.isMounted) {
let milliseconds = nextProps.venuesBonusOfferDuration * 1000;
this.source = timer(milliseconds);
this.firstTimerSubscription = this.source.subscribe(val => {
console.log("hiding bonus offer");
this.firstTimerSubscription.unsubscribe();
this.props.hideBonusOffer();
this.secondTimerSubscription = bonusApiTimer.subscribe(val => {
console.log("caling timer" + val);

this.props.getVenuesBonusOffer(
this.props.venues.venues.id,
this.props.uid,
this.props.accessToken
);
});
});
//}
} else {
try {
if (this.secondTimerSubscription != undefined) {
this.secondTimerSubscription.unsubscribe();
console.log("secondTimer UNSUBSCRIBED");
}
if (this.firstTimerSubscription != undefined) {
this.firstTimerSubscription.unsubscribe();
console.log("firstTimer UNSUBSCRIBED");
}
} catch (error) {
console.log(
"error when removing bonusoffer timer" + JSON.stringify(error)
);
}
//}
}
}

`

问题是如果我尝试取消订阅这个 * this.firstTimerSubscription* 和 this.secondTimerSubscription 这样
try {
if (this.secondTimerSubscription != undefined) {
this.secondTimerSubscription.unsubscribe();
console.log("secondTimerunmount UNSUBSCRIBED");
}
if (this.firstTimerSubscription != undefined) {
this.firstTimerSubscription.unsubscribe();
console.log("firstTimerunmount UNSUBSCRIBED");
}
} catch (error) {
console.log("error bonusoffer timer" + JSON.stringify(error));
}

它仍然在计时器内打印日志,例如“隐藏奖金优惠”和“调用计时器”。

有人可以指出这个问题。自从我进入这个以来已经一天了。

任何帮助表示赞赏。

最佳答案

问题是您多次订阅(每当组件收到 Prop 时)并将最新订阅重新分配给 firstTimerSubscriptionsecondTimerSubscription引用。但是这样做,订阅不会神奇地消失。看看它是如何工作的 here is a demo :

const source = timer(1000, 1000);

let subscribe;
subscribe = source.subscribe(val => console.log(val));
subscribe = source.subscribe(val => console.log(val));

setTimeout(() => {
subscribe.unsubscribe();
}, 2000)

即使您取消订阅,第一个订阅也会继续发出。问题是您丢失了对它的引用,因此您现在无法取消订阅。

简单的解决方法是检查您是否已经订阅,如果是,则取消订阅, 订阅前 :
this.firstTimerSubscription ? this.firstTimerSubscription.unsubscribe: false;
this.firstTimerSubscription = this.source.subscribe(...

关于reactjs - 取消订阅 rxjs 中的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59169921/

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