我花了一些时间阅读了一些关于 useEffect 钩子的其他解决方案,但我对它还是很陌生。有人可以向我解释我如何取消我的钩子中的订阅吗?
我知道应该有退货,但我不太确定在这种情况下我应该退货...如果您需要更多信息,请告诉我! 提前致谢! 这是我的代码片段:
const userAppointments = firestore.collection("customers").doc(`${userData.userId}`)
userAppointments.collection("appointments").where("serviceComplete", "==", true)
.onSnapshot((querySnapshot) => {
var appts = [];
querySnapshot.forEach((doc) => {
appts.push(doc.data());
});
setAppointments(appts)
})
}, [])```
答案 0 :(得分:0)
如果你从 useEffect
返回一个函数,当组件从小部件树中移除时,React 将调用该函数。
由于 Firestore 的 onSnapshot
返回的就是这样的取消订阅,您只需从 useEffect
调用中返回该取消订阅:
useEffect(() => {
const userAppointments = firestore.collection("customers").doc(`${userData.userId}`)
return userAppointments.collection("appointments").where("serviceComplete", "==", true)
.onSnapshot((querySnapshot) => {
var appts = [];
querySnapshot.forEach((doc) => {
appts.push(doc.data());
});
setAppointments(appts)
})
}, [])