React中如何从异步函数获取数据并用于组件渲染?
问题:如何从异步函数获取数据并在React组件中展示?
我搞不懂怎么从异步函数返回数据并在React组件里使用。不知道如何把Promise或者异步函数中的数据传递给可用于组件的普通函数,因为我清楚不能直接从异步函数向组件返回内容。
我想在将数据赋值给UserProfile对象后,展示它的hobbies属性,能不能给我指条正确的方向?
相关代码
class UserProfile{ constructor(hobbies) { this.hobbies = hobbies; } } const userProfileConverter = { toFirestore: (UserProfile) => { return { hobbies: UserProfile.hobbies } }, fromFirestore: (snapshot, options) => { const data = snapshot.data(options); return new UserProfile(data.hobbies); } } export const GetUserProfile = async () => { return new Promise(function (resolve, reject){ onAuthStateChanged(auth, async (user) => { if (user) { console.log('Reached this point!') const uid = user.uid; console.log('uid: ', uid); // const docRef = doc(db, "users", "profile", "hobbies", uid) const docRef = doc(db, "users", uid, "profile", "hobbies").withConverter(userProfileConverter); const docSnap = await getDoc(docRef); if (docSnap.exists()) { const userProfile = docSnap.data(); console.log('data: ', docSnap.data()); console.log('User Profile obj data: ', userProfile) resolve(userProfile); } } else { console.error('No signed in user!') reject('No signed in user.'); } }) }) } const displayUserProfile = () => { GetUserProfile().then((userProfile) => { return( <> <h1> {userProfile.hobbies} </h1> </> ); }); } export default displayUserProfile;
我尝试过的方法
- 在
GetUserProfile函数的onAuthStateChanged中返回数据(我知道这是错误的做法) - 尝试从Promise返回数据,但始终不知道如何将数据拿到Promise或异步函数外部使用
内容的提问来源于stack exchange,提问作者oreos
相关产品推荐
相关产品推荐

