gpt4 book ai didi

javascript - 获取 Firebase doc.data 未定义

转载 作者:行者123 更新时间:2023-12-02 22:23:53 25 4
gpt4 key购买 nike

我正在尝试从我的 Firebase 集合中获取数据。当我安慰的时候。 doc.data().name 它返回名称,但是当我尝试将 doc.data().name 分配给变量时,它向我显示未定义的错误。我正在使用 Vuex 和 firebase。

created() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user.uid);
firebase.firestore().collection("profiles").doc(user.uid)
.get()
.then(function(doc) {
console.log("Document data:", doc.data().name); // Getting value from firebase
this.profile.name = doc.data().name; // Getting Undefined Here
})
.catch(function(error) {
console.log("Error getting document:", error);
});
} else {

}
});
}


data() {
return {
profile: {
name: null
}
};
},

最佳答案

更改此:

          .then(function(doc) {
console.log("Document data:", doc.data().name); // Getting value from firebase
this.profile.name = doc.data().name; // Getting Undefined Here
})

进入此:

          .then((doc) => {
console.log("Document data:", doc.data().name); // Getting value from firebase
this.profile.name = doc.data().name; // Getting Undefined Here
})

使用文档中的箭头函数:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope

关于javascript - 获取 Firebase doc.data 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com