簡體   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