React-Firebase如何通过Project的userId获取Users集合的userName?
解决Firestore通过Project的userId获取对应userName的问题
你遇到的问题是因为Firestore的get()方法是异步操作,它返回的是一个Promise对象,而非直接的用户数据,所以直接赋值给userName并渲染会显示Promise而不是实际的userName。
可以通过React的状态管理和副作用处理来解决这个问题,具体实现如下:
import { useState, useEffect } from 'react'; const Summary = ({ project }) => { const [userName, setUserName] = useState(''); const [isLoading, setIsLoading] = useState(true); useEffect(() => { // 确保userId存在再发起请求 if (!project.userId) return; firebase.firestore().collection("users").doc(project.userId).get() .then(doc => { if (doc.exists) { // 从用户文档中取出userName字段 setUserName(doc.data().userName); } else { console.log("对应用户文档不存在"); setUserName('未知用户'); } setIsLoading(false); }) .catch(error => { console.error("获取用户数据失败:", error); setUserName('获取失败'); setIsLoading(false); }); }, [project.userId]); // 依赖userId,当它变化时重新请求数据 if (isLoading) { return <div>加载中...</div>; } return ( <div> {userName} </div> ) }
关键说明:
- 使用
useState维护用户名称和加载状态,确保数据变化时组件能重新渲染 useEffect的依赖数组加入project.userId,保证userId更新时自动重新请求对应用户数据- 处理了文档不存在、请求失败的异常情况,避免显示异常内容
- 加入加载状态提示,提升用户等待体验
内容的提问来源于stack exchange,提问作者shinzo_abe
相关产品推荐
相关产品推荐

