首页 > 解决方案 > 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

非常感谢您!

标签: javascriptreactjsfirebasereact-nativefirebase-realtime-database

解决方案


数据从 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);
    };
};

另见:


推荐阅读