我编写了以下代码来呈现一些帖子(这些帖子存储在Cloud Firestore实例中)。我正在使用mithril.js。
let SummaryPostView = {
posts: [],
view: function () {
let query = blogModels.postModel.getNLatest(20, "created");
query.then(function (data) {
this.posts = data;
console.log("INSIDE VALUE: ");
console.log(this.posts);
});
console.log("OUTSIDE VALUE: ");
console.log(this.posts);
}
};
在函数外部,this.posts
的值与this.posts inside the function.
的值不同。由于this
的行为可能令人困惑,我还尝试了以下代码:
let SummaryPostView = {
posts: [],
view: function () {
let query = blogModels.postModel.getNLatest(20, "created");
var x = [];
query.then(function (data) {
x = data;
console.log("INSIDE VALUE: ");
console.log(x);
});
console.log("OUTSIDE VALUE: ");
console.log(x);
}
};
为回应Chris Sandvik的回答,我还尝试了以下代码
let SummaryPostView = {
posts: [],
view: function () {
let query = blogModels.postModel.getNLatest(20, "created");
query.then(function (data) {
this.posts = data.docs.map(function (doc) {
let out = doc.data();
out.id = doc.id;
return out;
});
console.log("INSIDE");
console.log(this.posts)
});
console.log("OUTSIDE");
console.log(this.posts);
}
};
答案 0 :(得分:1)
由于您的输出是QuerySnapshot,因此您需要像这样访问数据:
query.then(function (data) {
this.posts = data.docs.map(doc => {
let out = doc.data();
out.id = doc.id;
return out;
});
});
您需要使用docs属性访问QuerySnapshot中的文档数组,并使用.data()
方法访问其数据。
此处有更多信息:https://firebase.google.com/docs/reference/js/firebase.firestore.QueryDocumentSnapshot.html