Javascript 访问Firebase中的2个关键数据
我可以访问key的第一个数据,但无法访问key path的下一个数据。当我输入'value'而不是'child_added'时,我会得到第一条路径的数据,但我需要访问phot中显示的路径中的所有数据Javascript 访问Firebase中的2个关键数据,javascript,firebase,firebase-realtime-database,Javascript,Firebase,Firebase Realtime Database,我可以访问key的第一个数据,但无法访问key path的下一个数据。当我输入'value'而不是'child_added'时,我会得到第一条路径的数据,但我需要访问phot中显示的路径中的所有数据 class App extends Component { constructor(props) { super(props) this.state = { users: [] } this.ex
class App extends Component {
constructor(props) {
super(props)
this.state = {
users: []
}
this.exportFile = this.exportFile.bind(this)
}
componentWillMount(){
this.getUsers()
this.getdataIDs()
}
getUsers() {
let users = []
// uncommented line gives an error
/*var eventID = firebase.database().ref(`conversationEnrolments`).once('value')*/
var path = firebase.database().ref(`conversationEnrolments`)
path.once('child_added', snapshot => {
snapshot.forEach(snap => {
users.push(snap.val())
})
this.setState({
users
})
})
}
您的问题来自这样一个事实:
once()
方法“只侦听指定事件类型的一个事件,然后停止侦听。”如文档中所述
因此,这就是为什么只获取一个子项的值,即具有-LDHYq…
id的子项
如果要获取conversationEnrolments
节点下的整个项目列表,请使用'value'
事件,并执行以下操作:
var ref = firebase.database().ref('conversationEnrolments');
ref.once('value', function (data) {
data.forEach(snap => {
console.log(snap);
console.log(snap.val());
});
});
然后,代码中还有第二个问题:因为once()方法是异步的,并且返回一个承诺(请参阅),您需要等待该承诺得到解决后才能使用用户
变量,如下所示。查看不同console.log()的执行顺序
let users = []
var ref = firebase.database().ref('conversationEnrolments')
ref.once('value', function (data) {
data.forEach(snap => {
console.log(snap);
console.log(snap.val());
users.push(snap.val());
});
}).then(() => {
//Here, the promise has resolved and you get the correct value of the users array
console.log("users AFTER promise has resolved");
console.log(users);
})
console.log("users BEFORE promise has resolved");
//Here the console.log prints the value of the array before the promise has resolved and.... it is empty!
console.log(users);
更新:如何将此代码封装到函数中
function getUsers() {
let users = []
var ref = firebase.database().ref('conversationEnrolments');
return ref.once('value', function (data) { //The function returns the result of the promise
data.forEach(snap => {
users.push(snap.val());
});
}).then(() => {
return users;
})
}
//The getUsers() is asynchronous
//Call it as follows: since it returns a promise, use the result within the then().
getUsers().then((users) => { console.log(users) });
从控制台它的工作完美!还有一个问题,无法将值推送到表中。以前,添加child_后,我可以将值推送到表中,但现在不行。@Jacob“不能推送值”的确切含义是什么。您是如何修改代码的?如果直接调用
getUsers()
函数,它将返回一个空的users
数组,原因与上述相同。您应该以这样的方式组织代码:users
数组仅在承诺得到解决时使用。@Jacob我已经更新了答案,以说明如何将代码封装到函数中。