首页 > 解决方案 > Can't store field value from firestore to variable

问题描述

I'm trying to store field value name read from a document in firestore users to variable userName so I can change the state value of userName. In general, how can I save field value to a variable and store it inside my component? Always, I appreciate everyone's help.

export default class Main extends Component {
state = {
    currentUser: null,
    userName: null
  };

getName = async () => {
    const { currentUser } = firebase.auth();
    this.setState({ currentUser });
    const uid = currentUser.uid;
    let userName = null;
    let docRef = await db.collection("users").doc(uid);
    docRef.get().then(doc => {
      userName = doc.data().name;
      console.log(userName);
      // this prints out "panda"
    });
    console.log(userName);
    // this prints out null
    this.setState({ userName });
  };

  componentWillMount() {
    this.getName();
  }

enter image description here

标签: reactjsfirebasereact-nativegoogle-cloud-firestore

解决方案


较低的console.log(userName)打印 null 因为您await是在文档 ref 的分配上设置的,而不是在.get(). .doc()返回一个引用,而.get()返回一个 Promise。

这会导致您的代码不等待由返回的 Promise.get()并移动通过整个块,从而显示一个null值,userName因为 Promise 尚未解决。有几种不同的方法可以解决这个问题。一种方法是将您setState()的块放入块内部,.then()如下例所示:

将您更改getName()为:

getName = async () => {
    const { currentUser } = firebase.auth();
    this.setState({ currentUser });
    const uid = currentUser.uid;
    await db
        .collection("users")
        .doc(uid)
        .get()
        .then(doc => {
            if (doc && doc.exists) {
                this.setState({ userName: doc.data().name });
            }
        });
};

我把它async/await留在那里,以防您将在此方法中添加更多逻辑,这需要等待 firebase 查询。如果没有,您可以同时删除asyncawait


推荐阅读