2016-09-13 33 views
2

我是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({})

非常感谢您的帮助。

回答

1

我不完全确定你的意思是被一个空数组调用。我可以想象的唯一原因是,如果您最初在该位置没有数据时才会被呼叫。如果是这样的原因,你可以用snapshot.exists()检测到它:

listen() { 
    var self = this 
    var currentUserID = firebase.auth().currentUser.uid 
    var postList = firebase.database().ref('/users/'+currentUserID+'/postKeys') 
    postList.on('value', function(snapshot) { 
     if (snapshot.exists()) { 
     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) 
     }) 
     } 
    }) 
    } 

如果不解决这个问题,你可以设置也再现一个jsbin?

+0

你,先生,是一个绅士和学者。非常感谢你的帮助。完美的感觉和作品。我很感激。 –

-1

可以使用setTimeout功能

setTimeOut(try,3000); 
function try(){ 
self.setState({ 
     postCount:posts.length, 
     dataSource:self.state.dataSource.cloneWithRows(posts) 
     }); 
} 

现在self.setState({})将查询后调用如果不改变3000至5000