【问题标题】:Can't store field value from firestore to variable无法将字段值从 firestore 存储到变量
【发布时间】:2020-04-18 04:46:21
【问题描述】:

我正在尝试将从 firestore users 中的文档读取的字段值 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();
  }

【问题讨论】:

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


    【解决方案1】:

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

    这导致您的代码不等待.get() 返回的 Promise 并移动通过整个块,从而显示 userNamenull 值,因为 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

    【讨论】:

    • 谢谢你,你的建议奏效了。出于好奇,我删除了 async 和 await 并将 doc.data().name 分配给在查询语句之前实例化的局部变量,但它仍然保持为空。你能解释一下为什么会这样吗?
    • 如果你想将变量设置在.then() 块的范围之外,那么你需要保持异步/等待,因为你需要在移动之前等待承诺解决继续其余的代码。如果此答案有帮助,请考虑将其设置为接受的答案:)
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多