【发布时间】:2019-03-20 12:57:16
【问题描述】:
我有一个名为 user 的类,其中包含用户类所需的所有方法和实例变量。在其中,我有一个方法负责将查询结果返回到 index.js 文件。在这个 index.js 文件中,我希望使用查询中的值设置状态。但这不起作用。
function collectres () {
var store ='';
var docRef = db.collection("cities").doc("SF");
docRef.get()
.then(function (doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
store = doc.data();// when referenced outside, it doesnt hold anything.
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function (error) {
console.log("Error getting document:", error);
});
return store; // returns nothing and seems to not notice the assignment.
}
上面的函数在我的用户类中。从索引中引用时,它看起来像这样。
Random() {
let a = '';
a = user.collectres();
this.setState({name:a});
console.log(this.state.name);
}
但是,这会将状态设置为先前的值。在查看控制台日志时,我注意到,日志记录的顺序首先从 index.js 控制台.log(this.state.name) 开始,但是我的收集资源的日志不应该首先显示。 任何帮助将不胜感激。
【问题讨论】:
标签: node.js reactjs google-cloud-firestore