如何将每个Firebase数据库条目传递给React-循环中的本机组件

时间:2018-07-16 19:29:47

标签: javascript reactjs firebase react-native firebase-realtime-database

我的Firebase项目看起来像- enter image description here

假设公告中有多个数据库条目,那么这是将每个公告条目传递给react-本机组件的最佳方法,该组件采用PopupLongtext作为props

我尝试过这样的事情:

returnNotificationCards() {
  var newArr = this.state.notContainer;
  return newArr.map((line) => {
    return <NotificationCards Popup = {
      line.Popup
    }
    longText = {
      line.Longtext
    }
    />
  });

}

componentDidMount() {
  let dataContainer
  firebase.database().ref('/announcements/').on('value', (snapshot) => {
    snapshot.forEach((childSnapshot) => {
      var childData = childSnapshot.val();
      dataContainer.push(childData)
    });
  });
  this.setState({
    notContainer: dataContainer
  })
}

但是代码不起作用。这里,Firebase数据应传递到的组件是NotificationCards

1 个答案:

答案 0 :(得分:0)

当我通过goToNotifications()从当前组件的父组件传递Firebase数据时,效果很好

goToNotifications() {
  var dataContainer = []
  firebase.database().ref('/announcements/').on('value', (snapshot) => {
    snapshot.forEach((childSnapshot) => {
      var childData = childSnapshot.val();
      dataContainer.push(childData);
    });
    Actions.Notifications({
      dataContainer
    })
  });
}

并通过NotificationCards通过当前组件返回到displayNotifi()组件

displayNotifi() {
  var fetcheData = this.props.dataContainer;
  return fetcheData.map((line) => {
    return <NotificationCards Popup = {
      JSON.stringify(line.Popup).replace(/\"/g, "")
    }
    longText = {
      JSON.stringify(line.Longtext).replace(/\"/g, "")
    }
    />
  });
}