【发布时间】:2016-05-01 15:15:19
【问题描述】:
我在 React-Native 中定义了一个函数,它从 Firebase 获取一个对象并将其内容推送到一个数组中。然而,虽然在我调用“push”之后数组被很好地填充,但它在 for 循环结束时是未定义的。我不知道为什么要清除它,因为我在 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)
});
【问题讨论】:
-
数组没有被清除,当你登录
NEWLIST 2时它还没有被填充。数据是异步加载的,您的代码(幸运的是用户)不等待结果。您的日志记录应按它们出现的顺序显示:NEWLIST 2,然后才NEWLIST。有关此现象的详细解释,请参阅stackoverflow.com/questions/14220321/…
标签: javascript arrays firebase react-native undefined