gpt4 book ai didi

javascript - 访问 Firebase 中的 2 个关键数据

转载 作者:行者123 更新时间:2023-11-30 14:32:57 25 4
gpt4 key购买 nike

我可以访问key的第一个数据,但是不能访问key path的下一个数据。当我键入“value”而不是“child_added”时,我得到第一条路径的数据,但我需要访问照片中显示的路径中的所有数据

    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
})
})
}

the values of the last path are not displayed

最佳答案

您的问题来自于 once() 方法“仅监听指定事件类型的一个事件,然后停止监听”这一事实。如文档中所述,here .

所以这就是为什么您只获得一个 child 的值(value),即具有 -LDHYq... id 的 child 。

如果要获取conversationEnrolments 节点下的整个项目列表,请使用'value' 事件并执行以下操作:

    var ref = firebase.database().ref('conversationEnrolments');
ref.once('value', function (data) {
data.forEach(snap => {
console.log(snap);
console.log(snap.val());
});
});

然后,您的代码中存在第二个问题:由于 once() 方法是异步的,并返回一个 promise (请参阅 doc),您需要等待此 promise 解决之前能够使用 users 变量,如下所示。查看不同 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) });

关于javascript - 访问 Firebase 中的 2 个关键数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com