You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:13:27