【问题标题】:duplicate values when I'm retrieving firebase users value in html table当我在 html 表中检索 firebase 用户值时重复值
【发布时间】:2020-08-12 09:00:49
【问题描述】:

在检索 firebase 数据库值时,这些值是重复的,我不知道为什么控制台只显示我的数据库中的 4 个值 take a look at this.

var ref = firebase.database().ref("users");
     ref.on("value", function(data){
      $('#table').empty()
        var content = '';
         data.forEach(function(childSnapshot){
             if (childSnapshot.exists()){
                var id = childSnapshot.key;
             var childData = childSnapshot.val();
             console.log(childData);
             console.log(id);

             content +='<tr>';
                content += '<td>' + childData.username + '</td>';
                content += '<td>' + childData.phone + '</td>';
                content += '</tr>';
         };
         $('#table').append(content);
        });

     });

【问题讨论】:

    标签: html node.js firebase firebase-realtime-database


    【解决方案1】:

    这是 firebase 侦听器的预期行为。如果您只想获取数据并完成处理,可以使用这个:

    var ref = firebase.database().ref("users");
    ref.once('value').then(function(snapshot) {// Do your stuff here}))
    

    看看这个问题: Firebase ref.on("value" is getting called even without a change in value - node.js

    [编辑] 这实际上是因为 $('#table').append(content) 行。把它从forEach 循环中去掉就可以了

    【讨论】:

    • 仍然得到重复值
    • @CloudMusic 即使你使用once ?
    • @CloudMusic 你到底需要监听数据的变化还是只需要在请求的那一刻获取数据?
    • 是的,即使使用once,我只想在重新加载页面或添加新子项时从数据库中获取值,这与我无关,为什么值重复以及如何避免这种情况
    • 是的,就是这样,谢谢你,有时候我看错了方向
    【解决方案2】:
        function SelectAllData() {
        firebase.database().ref('reminders').on('value',
            function (AllRecords) {
                AllRecords.forEach(
                    function (currentRecord) {
                        var task = currentRecord.val().task;
                        var  description = currentRecord.val().description;
                        var date = currentRecord.val().date;
                        AddItemsToTable(task, date, description);
                    }
                );
            });
    }
    window.onload = SelectAllData;
    
    //-----------------filling up the table----------------------------------//
    
    function AddItemsToTable(task, date, description) {
        var tbody = document.getElementById('tbody1');
        var trow = document.createElement('tr');
        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');
        td1.innerHTML = task;
        td2.innerHTML = date;
        td3.innerHTML = description;
        trow.appendChild(td1);
        trow.appendChild(td2);
        trow.appendChild(td3);
        tbody.appendChild(trow);
    } 
    

    这是我使用的,我没有使用 jQuery。我遇到了同样的问题,它只是再次打印整个表格。我将如何解决它。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多