无法将项目添加到数组react native中



我想在查询我的实时数据库后访问我的数组,但在提取一个项目并将其添加到我的数组后记录一个空数组。你知道是什么引起的吗?下面是我的代码:

const chatBox = async () => {
let array_Message_ = [];
try {
setLoading(true);
db.ref(`messages/`).once(`value`, snapshot => {
if(snapshot.exists() == true) {
snapshot.forEach(function(childSnapshot){
if(childSnapshot.key.includes(auth().currentUser.uid)){
var otherUserId = childSnapshot.key.replace(auth().currentUser.uid,"");
db.ref('messages').child(childSnapshot.key).orderByChild("sentWhileBlocked").equalTo(false).limitToLast(1).on('value',(dataSnapshots) => {
if (dataSnapshots.val()) {
for (let key in dataSnapshots.val()) {
db.ref(`users`).on(`value`, user_snapshot => {
user_snapshot.forEach(function(user_childSnapshot){
if(otherUserId == user_childSnapshot.key) {
array_Message_.push({text:dataSnapshots.val()[key].text,timestamp:dataSnapshots.val()[key].timestamp, username: user_childSnapshot.val().username, messageKey:key, key:dataSnapshots.key})
}
})
});
}
}
});
}
})
console.log("array: "+JSON.stringify(array_Message_))
setmessagesWithPhotos(array_Message_);
}
});
} catch(err) {console.log(err);}
}

console.log最有可能在array_Message_之前运行。推,因为db。ref(users)。On和其他类似的操作都是异步操作。所以不要在最后写semessageWithPhotos而是在最后一个回调

const chatBox = async () => {
let array_Message_ = [];
try {
setLoading(true);
db.ref(`messages/`).once(`value`, snapshot => {
if(snapshot.exists() == true) {
snapshot.forEach(function(childSnapshot){
if(childSnapshot.key.includes(auth().currentUser.uid)){
var otherUserId = childSnapshot.key.replace(auth().currentUser.uid,"");
db.ref('messages').child(childSnapshot.key).orderByChild("sentWhileBlocked").equalTo(false).limitToLast(1).on('value',(dataSnapshots) => {
if (dataSnapshots.val()) {
for (let key in dataSnapshots.val()) {
db.ref(`users`).on(`value`, user_snapshot => {
user_snapshot.forEach(function(user_childSnapshot){
if(otherUserId == user_childSnapshot.key) {
array_Message_.push({text:dataSnapshots.val()[key].text,timestamp:dataSnapshots.val()[key].timestamp, username: user_childSnapshot.val().username, messageKey:key, key:dataSnapshots.key})
}
})
console.log("array: "+JSON.stringify(array_Message_))
setmessagesWithPhotos(array_Message_);
});
}
}
});
}
})
}
});
} catch(err) {console.log(err);}

}

相关内容

  • 没有找到相关文章

最新更新