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

React Native中Firestore文档引用ID始终为undefined问题求助

问题解决:Firestore文档ID显示undefined的原因及修复方案

你的问题出在**addDoc是异步操作**,它返回的是一个Promise对象,而非直接的文档引用实例。你当前代码直接访问docRef.id时,Promise还未完成,自然拿不到真实的文档ID,但Firestore后台会在Promise执行完成后创建文档,所以数据库里能看到ID。

修复后的代码示例

用async/await处理异步逻辑,确保拿到完成后的文档引用:

const handleSignUp = () => {
  createUserWithEmailAndPassword(auth, email, password)
    .then(async (userCredentials) => { // 添加async标记
      const user = userCredentials.user;
      console.log("Registered with: ", user.email);
      console.log("Welcome", name);
      try {
        const docRef = await addDoc(collection(db, "userInfo"), { // 添加await等待异步完成
          fullname: name,
          userID: uID,
        });
        console.log("Success writing document!", docRef.id, "yay");
        // 这里可将docRef.id存入状态或传递给其他页面,示例:
        // setDocumentId(docRef.id);
        // navigation.navigate('OtherScreen', { docId: docRef.id });
      } catch (e) {
        console.error("Error adding document: ", e);
      }
    })
    .catch((error) => alert(error.message));
};

关键说明

  • await会等待addDoc执行完成,此时docRef才是真实的文档引用实例,能正常访问id属性。
  • 获取到docRef.id后,你可以把它存在组件状态(比如useState)里,或者在导航到其他页面时作为参数传递,后续就能用这个ID对该文档进行更新、添加字段等操作。

内容的提问来源于stack exchange,提问作者davidocodes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:40:25