我是Firebase的新用户,并将其与React Native结合使用。我正在尝试使用来自Firebase的数据填充ListView。我看到我现在可以在Firebase中使用Promises,但是,似乎我不能将它们与.on()
并仅与.once
一起使用。因为我需要听取更改,所以我需要使用.on()
。如何确保在Firebase查询填充数组后调用setState?
现在我面临的挑战是,我想确保在从Firebase检索数据(并且仅在此之后)设置状态。我的代码如下:
listen() {
var self = this
var currentUserID = firebase.auth().currentUser.uid
var postList = firebase.database().ref('/users/'+currentUserID+'/postKeys')
postList.on('value', function(snapshot) {
var posts = []
snapshot.forEach((child)=> {
var postID = child.val().postID
var postRef = firebase.database().ref('posts/'+postID)
postRef.orderByChild('sortedDateInMilliseconds').on('value', function(postSnap) {
posts.push(postSnap.val())
})
})
self.setState({
postCount:posts.length,
dataSource:self.state.dataSource.cloneWithRows(posts)
})
})
}
的结果是,我最初得到一个空的观点,因为查询填充柱阵列之前render()
被调用。有谁知道如何确保在查询填充数组后调用self.setState({})
?
非常感谢您的帮助。
你,先生,是一个绅士和学者。非常感谢你的帮助。完美的感觉和作品。我很感激。 –