我在下面的代码中使用派生存储。它感觉像一个奇怪的构造,因为我只对动态$session依赖使用派生构造并获得normData。但与$norm不同。我只使用$norm一次来启动派生存储。
尽管如此,它似乎运作良好。但是如果$session改变的话,我必须续订。是否可以在不取消订阅的情况下更新RxFire /RxJ订阅?
let normDocRef = null;
let normData = null;
let normSubscription = null;
const norm = derived(
session,
$session => {
normDocRef = db.doc(`uploads/${$session.a_id}_${$session.year}`);
// renew the subscription if $session changes
if (normSubscription)
normSubscription.unsubscribe();
normSubscription = doc(normDocRef).subscribe(snapshot => {
if (snapshot.exists) {
normData = snapshot.data();
} else {
normData = null;
};
});
},
);
$norm; // kick off the derived store to monitor $session
// show the data and updates
$: console.log(normData);
onDestroy(() => {
if (normSubscription) normSubscription.unsubscribe();
}); Update:我可以使用派生存储的集合和返回选项来更改真正的$norm Svelte存储中的$norm。下面的代码在我自己的答案。
但真正的问题是:我能更新订阅吗?更改订阅而不取消订阅?
发布于 2019-11-12 10:16:11
我已经有了答案,但没有意识到。
在派生的存储代码下面,使用set()和with ()选项。
当会话更改时,返回()将自动取消订阅。
所以还是取消订阅而不是更新..。但这感觉很好。好的!
let normDocRef = null;
let normSubscription = null
const norm = derived(
session,
($session, set) => {
normDocRef = db.doc(`uploads/${$session.a_id}_${$session.year}`);
normSubscription = doc(normDocRef).subscribe(snapshot => {
if (snapshot.exists) {
set(snapshot.data());
} else {
set({}); // clear
};
});
return () => {
normSubscription.unsubscribe();
};
}, {} // initial value
);
$: console.log('$norm', $norm); // Now it is a real store
onDestroy(() => {
if (!normSubscription.closed) {
normSubscription.unsubscribe();
}
});API文档派生存储:
从一个或多个其他商店派生存储。每当这些依赖项发生变化(比如$session),回调就会运行。
如果您从回调中“返回一个函数”,则当a)回调再次运行(因为依赖项更改)时,它将被调用(在回调之前),或b) .
发布于 2019-11-12 07:44:08
好吧,大致了解一下你想在这里描述的。
当变量/存储发生更改时,您实际上可以使用反应申报来执行代码。
在本例中,要执行重新订阅方法:
let normDocRef = null;
let normData = null;
let normSubscription = null;
$: {
normDocRef = db.doc(`uploads/${$session.a_id}_${$session.year}`);
// renew the subscription if $session changes
if (normSubscription) {
normSubscription.unsubscribe();
normSubscription = doc(normDocRef).subscribe(snapshot => {
if (snapshot.exists) {
normData = snapshot.data();
} else {
normData = null;
};
});
}
}
onDestroy(() => {
if (normSubscription) normSubscription.unsubscribe();
}); 这里的关键是,在编译该代码时,Svelte知道该块依赖于$session,因此每当$session更改时,它将重新执行代码块。
如果要将其重构为另一个函数,则需要确保Svelte知道该函数依赖于$session,即:
$: resubscribe_norm($session);在这里,Svelte可以看出,如果$session改变了,需要再次调用resubscribe_norm。
https://stackoverflow.com/questions/58810550
复制相似问题