无法将字段值从Firestore存储到变量

时间:2019-12-28 18:44:21

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

我正在尝试将在Firestore 用户中从文档中读取的字段值 name 存储为变量 userName ,以便更改状态值用户名。通常,如何将字段值保存到变量中并将其存储在组件中?一直以来,我都很感谢大家的帮助。

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

1 个答案:

答案 0 :(得分:1)

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

这导致您的代码不等待.get()返回的Promise并移动通过了整个块,从而由于{Promise尚未解决,因此显示null的{​​{1}}值。有几种不同的方法可以解决此问题。一种方法是将userName放在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 }); } }); }; 留在了那里,以防您在此方法中添加进一步的逻辑,这将需要等待Firebase查询。如果没有,则可以同时删除async/awaitasync