因此,我得到了一个带有Firebase配置的屏幕,另一个应该调用数据。我想了解最新信息。到目前为止,我有以下代码:
export const firebaseFetchProfileItem = (category) => {
var snap;
database
.ref("users/" + authentification.currentUser.uid + "/profile/" + category)
.on("value", function (snapshot) {
snapshot.val() ? (snap = snapshot.val()) : undefined;
}),
function (error) {
log.error(error);
};
return snap;
};
它工作正常,因为它不会在我第一次进入屏幕时更新值,而是仅在第二次打开应该显示值的特定屏幕后才更新。
在另一个屏幕中,将像这样调用这些值:
componentDidMount() {
this.state.item.bday = firebaseFetchProfileItem("bday");
}
我尝试执行以下操作:
export const firebaseFetchProfileItem = (category) => {
return (
database
.ref("users/" + authentification.currentUser.uid + "/profile/" + category)
.on("value", function (snapshot) {
return snapshot.val() ? (snapshot.val()) : undefined;
}),
function (error) {
log.error(error);
};
)
};
但是没有运气,它返回[匿名函数],从而给出组件不能为函数等的错误。当我登录snapshot.val()时,我得到了正确的生日。因此,我知道错误在于获取价值。
我还尝试了以下方法:
export const firebaseFetchProfileItem = (category, item) => {
database
.ref("users/" + authentification.currentUser.uid + "/profile/" + category)
.on("value", function (snapshot) {
snapshot.val() ? (item = snapshot.val()) : undefined;
}),
function (error) {
log.error(error);
};
};
和
componentDidMount() {
firebaseFetchProfileItem("bday", this.state.item.bday);
}
但是也没有运气..我要去哪里错了?如何始终显示更新的值?我还尝试了一些使用Promise和异步调用的方法,但是当我这样做时,它没有按计划进行,并且获取功能返回了Promise。我也尝试在同一屏幕上使用这些功能,但没有显示任何区别..有点无望的atm:D
提前非常感谢您!
Data is loaded form Firebase asynchronously, which means you can't return it from
firebaseFetchProfileItem
. Instead what you'd do is havefirebaseFetchProfileItem
put the data into the state once it's loaded, which then ensures that React repaints the UI based on the new data (including when that data is updated in the database).另请参阅: