【问题标题】:Firebase database and react nativeFirebase 数据库和本机反应
【发布时间】:2017-08-05 13:07:46
【问题描述】:

以下是数据库的示例结构。

root: {
  users: {
    user_uid_0: {
      name: 'AJ',
      age: 20,
      gender: 'male'
    }
  }
}

以下是我从 Firebase 获取数据的方式:

getData(myValue) {

  // direct ref to a key of 'name' from user_uid_0
  const name = firebase.database().ref('/users/user_uid_0/name');

  // name will go through a listener
  name.on('value', (snapshot) => {
    // define myValue to the snapshot
    myValue = snapshot.val()
    // this.myValue = snapshot.val() tried this...
  });

  // spit out myValue which we defined
  // myValue should be 'AJ'
  // but its not... its undefined
  return myValue;
  // im guessing because myValue is actually not defined...
  // then how do I define it with my snapshot.val()?
}

下面是一个反应原生组件,显示函数返回的内容。

// this should return the string 'AJ' from myValue
// this returns nothing
<Text>{this.getData()}</Text>

以下是我在控制台登录时得到的结果。

// undefined is what I get
console.log(this.getData());

既然这行不通,那又如何呢?如何通过 ref 获取数据并显示它?请帮忙。这几天我一直在为此苦苦挣扎。

【问题讨论】:

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


    【解决方案1】:

    试试这样的 -

    getData = async () => {
      const name = firebase.database().ref('/users/user_uid_0/name');
    
      var data = await name.once('value')
        .then(snapshot => {
          console.log("value", snapshot.val());
          return snapshot.val();
        })
        .catch(e => {
          console.log("firebase error", e);
          return null;
        });
    
      return data;
    }
    

    【讨论】:

    猜你喜欢
    • 2019-08-29
    • 2019-05-10
    • 1970-01-01
    • 2019-03-18
    • 2021-12-09
    • 2020-02-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    相关资源
    最近更新 更多