为什么输出重复?

时间:2019-02-25 08:33:53

标签: firebase react-native firebase-realtime-database foreach

从firebase数据库获取数据并将我的输出输出到模拟器是重复的。我知道为什么将数据两次推送到“项”。我该如何解决此问题,并将每个孩子中的项目仅推送到“ addData”一次?

我的代码:

      constructor(props) {
        super(props);
        this.state = {
            arrData:[]
        };
    }

    componentDidMount = () => {
      var self = this;
       var items = [];
       database.ref("eventAttenders/2188058178082419").orderByKey().once("value")
         .then(function(snapshot) {
           snapshot.forEach(function(childSnapshot) {
             var key = childSnapshot.key;
             const key = childSnapshot.key;
             database.ref(`users/${key}`).once("value")
               .then(function(snapshot) {
                 snapshot.forEach(function(childSnapshot) {
                   var data = snapshot.val();
                   items.push({
                     name: data.name,
                     phone: data.phone,
                   });
               });

             });

         });

       });
       self.setState({arrData: items})
 }

数据库屏幕截图:

enter image description here

模拟器屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:0)

由于您不需要在snapshot.forEach(function(childSnapshot) {中添加push方法,因此请尝试将其删除。

componentDidMount = () => {
      var self = this;
       var items = [];
       database.ref("eventAttenders/2188058178082419").orderByKey().once("value")
         .then(function(snapshot) {
           snapshot.forEach(function(childSnapshot) {
             var key = childSnapshot.key;
             const key = childSnapshot.key;
             database.ref(`users/${key}`).once("value")
               .then(function(snapshot) {
                   var data = snapshot.val();
                   items.push({
                     name: data.name,
                     phone: data.phone,
                   });
             });

         });

       });
       self.setState({arrData: items})
 }