React-NativeでFirebaseからオブジェクトを取得し、その内容を配列にプッシュする関数を定義しました。しかし、配列は 'push'を呼び出した後に正しく配置されていますが、forループの最後には定義されていません。なぜ私はそれがクリアされているのかわからない、私はforループの外に配列を定義しているので、私は何かが不足している場合のために余分なペアのペアを求めるだろうと思った。配列はjavascript関数の外で未定義ですか?
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'だけです。この現象についての詳しい説明は、http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –
を参照してください。[私の変数は変更後も変更されませんそれは関数の中で?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)と[ループ内のJavaScriptクロージャ](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) –