[英]react native as soon as is array.push done
有什么方法可以捕获array.push函数何时完成? 我从Firebase数据库获取数据,然后将数据推送到数组(状态)。 不幸的是,正如我注意到的那样,它每项更改一次状态。
检查屏幕以更好地了解
我在数据库中有2个对象。
有代码:
componentWillMount(){
const self = this;
const rootRef = firebase.database().ref('/users/' + firebase.auth().currentUser.uid);
const ref = rootRef.child("MyTeams");
let teamsArr = [];
ref.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
self.setState({TeamName: childSnapshot.val()});
teamsArr.push(self.state.TeamName);
self.setState({TeamsToMap: teamsArr});
self.setState({Loaded: true});
console.log('Here: ' + self.state.TeamsToMap);
})
})
.catch((error) =>{
alert(error.message);
})
};
WriteTeams(navigation){
if(this.state.TeamsToMap.length > 0 && this.state.Loaded === true){
console.log('Somewhere: ' + this.state.TeamsToMap.length);
}
}
由于要遍历快照,因此会多次修改阵列。 如果只想在修改完成后打印它:在循环之后移动console.log()
语句。
ref.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
self.setState({TeamName: childSnapshot.val()});
teamsArr.push(self.state.TeamName);
self.setState({TeamsToMap: teamsArr});
self.setState({Loaded: true});
})
console.log('Here: ' + self.state.TeamsToMap);
})
由于snapshot.forEach()
teamsArr.push()
snapshot.forEach()
和teamsArr.push()
在此处都是同步的,因此,在完全填充teamsArr
之后, console.log()
将运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.