【问题标题】:React Native how to read Real Time Database FirebaseReact Native 如何读取实时数据库 Firebase
【发布时间】:2020-05-23 16:14:27
【问题描述】:

所以我得到了一个带有 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

非常感谢您!

【问题讨论】:

  • 我想你会想给firebaseFetchProfileItem 提供一个回调,这样它就知道在找到新值时要做什么。你不能从一个函数返回多个值,所以对返回值做任何事情都是行不通的。 Promise 也对你毫无帮助,因为它们不处理持续的变化。

标签: javascript reactjs firebase react-native firebase-realtime-database


【解决方案1】:

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

另见:

【讨论】:

  • 非常感谢您的回答,给了我一些宝贵的见解!
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多