【问题标题】:Why does this function return false in React Native?为什么这个函数在 React Native 中返回 false?
【发布时间】:2020-06-05 02:39:02
【问题描述】:

功能

checkIfSeen = (uid, news_id) => {
  var seen = false;
  const docRef = DB.informationsCollection.doc(news_id).collection('users').doc(uid);
  docRef.get()
    .then((docSnapshot) => {
      if (docSnapshot.exists) {
        seen = true;
        console.log(seen);
        // returns true
      }
    });
  console.log(seen);
  // returns false
}

问题

它在if (docSnapshot.exists) { 之后返回true,但在函数的最后一个返回false。

有人知道为什么会这样吗?

如果您能给我任何建议,我将不胜感激。

更新

checkIfSeen = (uid, news_id) => {
  const docRef = Fire.shared.informationsCollection.doc(news_id).collection('users').doc(uid);
  docRef.get()
    .then((docSnapshot) => {
      if (docSnapshot.exists) {
        this.alreadySeen();
      } else {
        this.notSeen();
      }
    });
}

alreadySeen = () => {
  return true;
}

notSeen = () => {
  return false;
}

【问题讨论】:

标签: javascript reactjs react-native google-cloud-firestore


【解决方案1】:

函数checkIfSeen 没有明确的返回类型。它将始终将undefined 返回给调用它的人。

函数内部还有一个异步活动,位于docRef.get()

这就是所谓的承诺。它在完成工作后执行then 块,将返回的数据传递给提供给then 函数的函数。

函数执行现在进入 then 块,不能同步返回到外部函数。

您可以在 then 函数中继续执行您的程序。喜欢

checkIfSeen = (uid, news_id) => {
  var seen = false;
  const docRef = DB.informationsCollection.doc(news_id).collection('users').doc(uid);
  docRef.get()
    .then((docSnapshot) => {
      if (docSnapshot.exists) {
        seen = true;

        // Do something here or invoke any other function
        renderUI();
        console.log(seen);
        // returns true
      }
    });
  console.log(seen);
  // returns false
}

【讨论】:

  • 谢谢。我添加了更新的代码,但它返回 undefined :( 如果您能检查一下,我将不胜感激。
猜你喜欢
  • 2021-12-21
  • 2019-05-20
  • 2018-08-27
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多