React Native集成Firebase时如何查询Firestore帖子及对应发布用户数据
解答
数据库结构合理性
你目前的库结构是Firestore的标准设计范式,完全可用:将帖子和用户分不同集合存储,通过userId关联,避免数据冗余,适合大多数中小规模应用场景。如果后续遇到高频列表页查询需要一次拉取大量帖子+对应用户信息的性能问题,再考虑将用户的高频展示字段(如昵称、头像)冗余存储到帖子文档中即可,当前阶段不需要调整结构。
现有代码的核心问题
- post的初始值错误设置为数组,单篇帖子应为对象类型,初始值设为
null更合理 - 两个异步查询逻辑顺序错误:获取帖子的请求是异步的,你在同步代码中直接取
post.userId时,帖子请求还未返回,此时拿到的是初始值的undefined,根本查不到对应用户 - 文档查询写法冗余:查询已知ID的单文档直接用
doc(文档ID).get()即可,不需要用where匹配文档ID - 用户查询的条件写反:
where的第一个参数是要匹配的字段名,应该是文档ID匹配传入的userId,而不是反过来
修正后代码
const [post, setPost] = useState(null); const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); // 可加加载状态提升体验 useEffect(() => { const fetchPostAndUser = async () => { try { // 1. 先查帖子详情 const postSnapshot = await firebase.firestore() .collection("allPosts") .doc(props.route.params.postId) .get(); if (!postSnapshot.exists) return; const postData = { id: postSnapshot.id, ...postSnapshot.data() }; setPost(postData); // 2. 拿到帖子里的userId后再查对应用户 const userSnapshot = await firebase.firestore() .collection("users") .doc(postData.userId) .get(); if (userSnapshot.exists) { setUser(userSnapshot.data()); } } catch (err) { console.log('数据加载失败', err); } finally { setLoading(false); } }; fetchPostAndUser(); }, [props.route.params.postId]); // 把postId加入依赖数组,参数变化时自动重新拉取
内容的提问来源于stack exchange,提问作者flaneurx
相关产品推荐
相关产品推荐

