【发布时间】:2020-05-12 11:57:30
【问题描述】:
我环顾四周,似乎找不到解决方案。非常感谢我能在这里得到的任何帮助.. 代码显然还有更多内容,但我相信我的错误就在这里的某个地方.. 我希望我的 allFirebaseItems 尽快成为一个完整且可用的对象,但我不知道完成它的方法。我很乐意提供所需的任何其他信息。
constructor(props) {
super(props);
this.state = {
allFirebaseItems: {},
};
}
componentDidMount() {
this.firebaseFetch();
}
//to get the items from firebase
firebaseFetch = () => {
const temp = {};
database.ref(authentification.currentUser.uid).on("value", (snapshot) => {
snapshot.forEach((category) => {
category.forEach((date) => {
if (!temp[date.key]) {
temp[date.key] = [];
}
date.forEach((itemKey) => {
var valuesToPush = {};
itemKey.forEach((element) => {
valuesToPush[element.key] = element.val();
});
temp[date.key].push(valuesToPush);
});
});
});
//gives me the object with the fetched information, works so far
console.log(JSON.stringify(temp));
//allFirebaseItems is still undefined and I don't know how to fix it
this.setState(
{allFirebaseItems: temp},
);
});
};
【问题讨论】:
-
你应该在database.ref的回调中使用setState
-
您如何检查或确认您的状态对象不是最新的?不要忘记
setState是异步的。如果您在渲染函数中阅读this.state.allFirebaseItems,那里是空的吗?那看起来像什么?
标签: javascript reactjs react-native firebase-realtime-database