[英]Array undefined outside of javascript function?
I've defined a function in React-Native that gets an object from Firebase and pushes its contents onto an array. 我已经在React-Native中定义了一个函数,该函数从Firebase获取对象并将其内容推送到数组中。 However, although the array is being populated fine after my call to 'push', it is undefined at the end of the for loop.
但是,尽管在我调用'push'之后可以很好地填充数组,但是在for循环的末尾未定义该数组。 I have no idea why it's being cleared, as I'm defining the array outside of the for loop, so I thought I'd ask for an extra pair of eyes in case I'm missing anything.
我不知道为什么要清除它,因为我是在for循环之外定义数组,所以我想我要多找几只眼睛,以防丢失任何东西。
var newList = [];
var arrayLength = userArray.length;
for (var i = 0; i < arrayLength; i++) {
var userRef = usersRef.child(userArray[i]);
userRef.once('value', function(snap) {
newList.push({
name: snap.val().name,
description: snap.val().description,
});
//this log statement prints out correct array
console.log("NEWLIST" + newList[i]);
});
//but array is undefined here
console.log("NEWLIST 2" + newList[i]);
}
this.setState({
current: this.state.current.cloneWithRows(newList),
past: this.state.past.cloneWithRows(oldList)
});
Read up on JavaScript's asynchronous nature. 阅读JavaScript的异步性质。 The once function takes a callback.
一次函数需要一个回调。 The console.log in the outer scope is executed before you push any items info your array.
在将任何项目信息推送到数组之前,将执行外部作用域中的console.log。
The code looks fine but what I think might be happening here is that userRef.once()
is an async call, and your outer console.log
is getting executed first. 代码看起来不错,但是我认为这里可能发生的是
userRef.once()
是一个异步调用,并且您的外部console.log
首先被执行。 And when the event triggers the callback your inner console.log()
prints the value 当事件触发回调时,内部
console.log()
打印值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.