javascript - React Native 如何读取实时数据库 Firebase
问题描述
所以我得到了一个带有 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;
};
它工作“okayish”,因为它不会在我第一次进入屏幕时更新值,但只有在我第二次打开应该显示值的某个屏幕之后。
这些值在另一个屏幕中是这样调用的:
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);
};
)
};
但没有运气,它返回 [Function anonymous] 并因此给出组件不能是函数等错误。当我记录 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 和异步调用的方法,但是当我这样做时,它并没有按计划工作,并且 fetch 函数返回了一个 Promise。我也尝试在同一个屏幕上使用这些功能,但它没有显示任何差异.. 有点绝望的 atm :D
非常感谢您!
解决方案
数据从 Firebase 异步加载,这意味着您不能从firebaseFetchProfileItem
. 相反,您要做的是firebaseFetchProfileItem
在数据加载后将数据置于状态,然后确保 React 根据新数据(包括该数据在数据库中更新时)重新绘制 UI。
export const firebaseFetchProfileItem = (category, item) => {
database
.ref("users/" + authentification.currentUser.uid + "/profile/" + category)
.on("value", function (snapshot) {
setState({ [category]: snapshot.val() });
}),
function (error) {
log.error(error);
};
};
另见:
推荐阅读
- python - 基于类的视图和查询集中 request.user 的 Python Django 最佳实践
- r - 使用 R 在 Firefox 中创建当前打开的 URL 的向量
- css - 如何从 Angular (2+) 生成缩小的 css
- installation - 在 R studio 1.2.1335 和 macOS Sierra 10.12.6 中使用 BiocManager::install 安装“org.Hs.eg.db”时出现问题
- sql - 有没有办法根据在 SELECT 语句中作为列名满足的多个条件来提取新计算?
- django - 使用频道 + Nginx + Daphne 部署 dockerized Django
- excel - 在用户窗体初始化上设置多个复选框
- rest - api 是否应该在返回响应之前更改其他系统状态?
- docker - 无法使用 shell 脚本启动 docker 容器
- faunadb - 如何在 FaunaDB 中获取嵌套文档?