gpt4 book ai didi

javascript - Tracker.autorun() 不会在 ReactiveVar 的每次更新时运行

转载 作者:行者123 更新时间:2023-11-27 22:50:32 25 4
gpt4 key购买 nike

我有一个 Meteor ReactiveVar,它用作数据存储中的更新触发器。然而,每次设置 react 变量时,跟踪器都不会运行。

似乎有时当快速连续设置状态时,跟踪器不会运行。

这是我商店的代码:

const myStore = {
states = {
...
},

updateTrigger = new ReactiveVar({ name: null, timeStamp: null }),

setState({ name, value }) {
this.states[name] = value;
console.log('Set State', name);
this.updateTrigger.set({ name, timeStamp: new Date().getTime() });
},
};

和跟踪器:

Tracker.autorun(() => {
const updateTrigger = myStore.updateTrigger.get();
console.log('Tracker', updateTrigger.name);
if (updateTrigger.name === state-two) myFunction();
});

控制台记录以下内容:

'Set State state-one' // update state-one
'Tracker state-one'
'Set State state-two' // update state-two
'Set State state-one' // update state-one
'Tracker state-one'
'Set State state-three' // update state-three
'Tracker state-three'
'Set State state-one' // update state-one
'Set State state-two' // update state-two
'Set State state-three' // update state-three
'Tracker state-three'

我不明白为什么会发生这种情况。

这似乎是一种竞争条件,因为它不区分记录哪些更新和不记录哪些更新。

状态更新非常频繁(每 1.5 秒状态一次,然后每秒左右更新一次其他状态)。

欢迎就问题所在或其他方法提出任何建议。

我可以使用 PubSub 包。一般来说,我不是 TrackerReactiveVar 的忠实粉丝,但我不确定这里的最佳实践是什么,而且我不想使用 Tracker +ReactiveVar 在某些地方,而 PubSub 在其他地方。

将每个单独的状态作为 ReactiveVar 并不是一种选择,因为我需要在更新时将状态保留到数据库。

最佳答案

这是由于Tracker's Flush Cycle .

来自跟踪器手册:

... by default, all changes to reactive values are batched up and put into effect all at once, when all JavaScript code has finished executing and the system is idle. ... This process ... is called flushing, and it's also possible to manually trigger it by calling Tracker.flush().

因此,在代码中添加显式刷新将产生所需的效果:

const myStore = {
states = {
...
},

updateTrigger = new ReactiveVar({ name: null, timeStamp: null }),

setState({ name, value }) {
this.states[name] = value;
console.log('Set State', name);
this.updateTrigger.set({ name, timeStamp: new Date().getTime() });
Tracker.flush(); // added this
},
};

关于javascript - Tracker.autorun() 不会在 ReactiveVar 的每次更新时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38096171/

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