如何通过useCollectionData Hook获取Firestore文档ID?
让useCollectionData返回Firestore文档ID的方法
方法一:使用useCollectionData的配置参数
useCollectionData本身支持传入第二个配置对象,其中的idField可以指定文档ID在返回对象中的字段名,直接让返回数据包含ID:
const messagesRef = collection(db, 'messages') const q = query(messagesRef, orderBy('createdAt'), limit(25)) // 配置idField为'id',返回的每个message会带文档ID const [messages, loading] = useCollectionData(q, { idField: 'id' })
这样messages数组里的每个对象都会多一个id字段,对应Firestore文档的ID。
方法二:用useCollection Hook手动处理(替代方案)
如果因为版本或其他原因无法使用上述配置,可改用useCollection获取查询快照,再手动提取ID和字段数据:
import { useCollection } from 'react-firebase-hooks/firestore' const messagesRef = collection(db, 'messages') const q = query(messagesRef, orderBy('createdAt'), limit(25)) const [snapshot, loading] = useCollection(q) // 遍历快照文档,合并ID和数据 const messages = snapshot?.docs.map(doc => ({ id: doc.id, ...doc.data() }))
useCollection返回的是QuerySnapshot对象,通过docs属性遍历每个文档实例,把doc.id和doc.data()的字段合并成新对象,就能得到包含ID的消息数组。
内容的提问来源于stack exchange,提问作者codelover1
相关产品推荐
相关产品推荐

