【问题标题】:Firestore get callFirestore 接听电话
【发布时间】:2020-09-26 19:01:49
【问题描述】:

我需要一些理解和解决方案。

我有一个单独的 js 文件,用于处理所有 api 调用。

所以我想在我的 HomeScreen 中从 Firestore 中获取数据。

在 then 调用的 Api 中,我得到了我的数据,但在主屏幕中,我只得到了一个 Promise。

我尝试了一些更改,但没有任何帮助。我不明白这个。 我如何在我的 HomeScreen 中获取数据?

我的代码有问题吗?

Api.js

export const getCurrentUserProfile = () => {
  if (firebase.auth().currentUser.uid) {
    const userDocID = firebase.auth().currentUser.uid;
    const docRef = db.collection('Users').doc(userDocID);

    docRef.get().then((doc) => {
      console.log(firebase.auth().currentUser.uid);
      if (doc.exists) {
        console.log(doc.data()); // return the data i need
        return doc.data();
      } else {
        console.log('No document for this ID: undefined');
      }

    }).catch((error) => {
      console.log('Error getting document', error);
    });
  }
  
}

HomeScreen.js

const user = getCurrentUserProfile();
console.log(user);
// And here i get this back:
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

const user = getCurrentUserProfile().then(data => console.log(data));
// this return as well undefined

非常感谢

【问题讨论】:

    标签: javascript google-cloud-firestore promise


    【解决方案1】:

    您需要记住,Promise 是异步的,基本上它们只是 - 承诺。如果您需要使用 Promise 中的实际数据,您有两种选择:

    • 在它们之后使用.then() (doc) 进行链式回调
    • 使用 await 关键字 (doc)

    其次,目前您不会从 getCurrentUserProfile() 函数返回任何内容。您需要返回docRef.get() 方法,它本身就是一个promise,并将解析为doc.data()

    例子:

    // option 1
    const user = getCurrentUserProfile().then(data => console.log(data));
    
    // option 2
    const user = await getCurrentUserProfile();
    console.log(user);
    

    请记住,您只能在异步函数中使用 await

    【讨论】:

    • 您好,感谢您的回复。我尝试了一下,但在选项 1 上我得到了 null。如果我在 api 中删除返回 null,我会得到 undefined 和一个错误
    • @juri88 在返回之前提取 doc.data() 会发生什么?像这样的东西:const response = doc.data(); return response;
    • 同样的错误:( TypeError: undefined is not an object (evaluating'(0,_Api.getCurrentUserProfile().then')
    • 哦,等等。尝试返回整个 docRef.get() 语句。所以在docRef.get().... 之前放一个return关键字
    • 谢谢,现在我得到了数据,但只有在 console.log(user);我得到另一个承诺?为什么 ?你知道吗?为什么我必须返回整个 doc.ref?
    【解决方案2】:

    现在我又遇到了一个错误。无效的挂钩呼叫。 Hooks 只能在函数组件的主体内部调用。但我只需要一次将用户初始化为使用状态来访问对象。我该怎么做?

    因为如果我在组件内移动代码,它会每秒运行一次...

    const [userObj, setUserObj] = useState({});
    getCurrentUserProfile().then(user => {
      setUserObj(user);
    });
    
    const HomeScreen = props => {
      return (
        <SafeAreaView style={globalStyles.container}>
          <Text style={globalStyles.h1}>Home</Text>
        </SafeAreaView>
      )
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多