这是我的代码:
constructor(props) {
super(props);
this.state = {
docs: []
};
}
async componentDidMount() {
await this.quizes();
console.log(this.state.docs);
}
quizes = () => {
firebase
.firestore()
.collection("quiz")
.get()
.then(result => {
const docs = result.docs.map(doc => {
return { uid: doc.id, ...doc.data() };
});
this.setState({ docs });
});
};
当我尝试使用console.log(this.state)
中的文档进行更新时,当前firestore
返回空文档。
答案 0 :(得分:2)
char* charS = malloc(sizeof(char) * 11);`
是异步的。如果您确定您的收藏集不为空,则可以使用以下方式查看状态:
setState
仅在完成设置状态的异步任务时运行作为this.setState({ docs }, () => console.log(this.state);
的第二个参数的函数,因此您将看到更新后的状态。
答案 1 :(得分:1)
要await
的{{1}}函数也必须是quizes
并使用await语法而不是promise。
例如,此代码应达到期望的结果:
async
编辑:
constructor(props) {
super(props);
this.state = {
docs: []
};
}
async componentDidMount() {
await this.quizes();
}
quizes = async () => {
let result = await firebase.firestore().collection("quiz").get()
const docs = result.docs.map(doc => {
return { uid: doc.id, ...doc.data() }
});
return this.setState({ docs }, () => {
console.log(this.state.docs);
});
};
使用回调。为了确保在记录时已设置状态,请在setState
函数中使用回调。