繁体   English   中英

为什么这个 function 在 React Native 中返回 false?

[英]Why does this function return false in React Native?

功能

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,但在 function 的最后一个返回 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;
}

function checkIfSeen没有明确的返回类型。 它总是会返回undefined给调用它的人。

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

这就是所谓的 promise。 当它的工作完成时,它执行then块,将返回的数据传递给 function 提供给then function。

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

您可以在 function 中继续执行您的程序。 喜欢

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM