异步分配后反应不渲染

时间:2020-07-31 05:17:21

标签: javascript firebase asynchronous google-cloud-firestore

我非常确定问题出在异步行为上。我认为是因为当userLinks.exists为true时,我的react应用程序才有条件地渲染,但这仅在firebase方法完成后才分配。关于如何解决此问题的任何建议?页面不断呈现空白屏幕并显示错误:

react-dom.development.js:13413 
Uncaught Error: Objects are not valid as a React child (found: [object Promise]). 
If you meant to render a collection of children, use an array instead.

app.js

const User = async ({ match, location }) => {

  const userLinks = await firebase.getUserInfo(match.params.user)

  return (
    <React.Fragment>
      { userLinks.exists ? <h1>Loaded and works!</h1> : <h1>Didn't work</h1> }
    </React.Fragment>

firebaseconfig.js

class Firebase {
  constructor() {
    firebase.initializeApp(firebaseConfig);
    this.auth = firebase.auth();
    this.db = firebase.firestore();
  }

  async getUserInfo (username) {
    let userInfo = { exists: false }
    await this.db.collection("users").doc(username).get().then(doc => {
      if (doc.exists) {
          console.log("Document data:", doc.data());
          userInfo.exists = true;
          userInfo = { ...userInfo, links: doc.data().links };
      } else {
          // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
    return userInfo;
  }

export default new Firebase();

2 个答案:

答案 0 :(得分:2)

使用async / await不会使代码突然同步运行。您仍然需要注意返还诺言和价值观,并将其鼓吹起来。

在您的代码中,我认为这样:

  async getUserInfo (username) {
    return await this.db.collection("users").doc(username).get().then(doc => {
      if (doc.exists) {
        return { exists: true, links: doc.data().links };
      } else {
        return { exists: false }
      }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    });
  }

答案 1 :(得分:0)

等待,等待诺言解决或拒绝。 尝试 返回Promise.resolve(userInfo);