【发布时间】: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