【发布时间】:2020-09-21 02:51:33
【问题描述】:
我想知道在异步函数中从 Firebase 获取多个数据以等待来自第一个请求的一些数据的最佳方法是什么。我现在正在使用此代码,但它不可靠,有时会中断说它无法获取第二次调用的数据,因为它是 undefined。
function useOccasion() {
const [occasionData, setOccasionData] = useState(null)
const [friend, setFriend] = useState(null)
let { occasion } = useParams()
useEffect(() => {
const unsubscribe = firestore.collection('occasions').doc(occasion)
.onSnapshot(async eventData => {
setOccasionData({id: eventData.id, ...eventData.data()})
let friendData = await firestore.collection("friends").doc(eventData.data().friend).get();
setFriend({id: friendData.id, ...friendData.data()});
})
return () => unsubscribe()
}, [occasion])
return [occasionData, friend]
}
如果有更强大的方法来实现这一点,那就太棒了。
【问题讨论】:
-
“有时说它无法获取第二次调用的数据,因为它是未定义的。” -> 你能提供更多细节吗?什么是未定义的?
eventData.data().friend? -
eventData.data().friend有时在第二次调用中未定义,因为此数据来自第一个请求。当我实际编码时,这个错误经常发生。当我保存时,它会触发热重载,这是大多数时候发生错误的时候。 -
"有时在第二次调用中未定义,因为此数据来自第一个请求。" -> 是否未定义,因为对于某些
occasion文档没有friend数据,或者因为存在获取friendsdoc 时是否有一些“真正的”错误? -
这是一个错误,我刷新它就恢复正常了。
-
您确定所有
occasion文档都有friend字段吗?
标签: reactjs firebase google-cloud-firestore react-hooks