javascript - React firebase 在第一次加载时会重复数据,但在刷新时加载时不会重复数据

标签 javascript reactjs firebase foreach firebase-realtime-database

我正在创建一个在提取数据后填充数据的表。问题是,在第一次渲染时,数据是重复的,因此表行也有重复项,但当重新加载页面时,数据不再重复。为什么我的数据在第一次加载时会 self 复制,但在之后的加载中却不会?

这是我的代码:

import React from 'react';
import { firebaseAuth } from './../config/constants'
import firebase from 'firebase'

class PeopleDash extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      uid: '',
      people: [],
      peopleTableArray: [["name", "dateOfBirth", "height", "doneWithSchool"]]
    };
  }

  componentWillMount() {
    this.setState({ people: [] });
  }

  componentDidMount() {
    firebase.auth().onAuthStateChanged(function (user) {
      if (user) {
        console.log(user.uid);
        this.setState({ uid: user.uid });
        this.setState({ people: [] });
        var firebaseChild = this.props.firebaseChild;
        const ref = firebase.database().ref().child(firebaseChild).child(user.uid);
        ref.once("value", function(snapshot){
          snapshot.forEach(function(data){
            this.setState({
              people: this.state.people.concat(data.val())
            })
            console.log(this.state.people);  //ISSUE

//问题:此时您可以看到控制台日志在第一页加载时重复,但之后没有任何加载

          }.bind(this));
        }.bind(this));
      } else {
        console.log("no data");
      }
    }.bind(this));
    console.log('componentDidMount ended and this.state.people = ' + {this.state.people});
  }

  render() {
    return (
      <div className="contentRow" id={this.props.id}>
        <div className="dynamicSnapshotTable">
        {
          // loop through each snapshot on firebase (for the user logged in)
          this.state.people.map((item, i) => {

            return (
              <div key={i} id={item.name} className="tableRowDiv">
              {
                this.props.tableArray.map((attribute, j) => {
                  return (
                    <div key={j} className="tableDataDiv">
                      {(this.props.tableArray[j] == 'doneWithSchool') ? (
                        (item[this.props.tableArray[j]]) ? ('tru') : ('fal')
                      ) : (
                        item[this.props.tableArray[j]]
                      )}
                    </div>
                  );
                })
              }

              </div>
            );
          })
        }
        </div>
      </div>
    );
  }
}

PeopleDash.propsTypes = {
  id: React.PropTypes.string,
  tableArray: React.PropTypes.array,
  firebaseChild: React.PropTypes.string,
};


export default PeopleDash;

提前谢谢您!

最佳答案

onAuthStateChanged 事件可能会触发多次。每次这样做,您都会向显示中添加更多的人。

要解决此问题,请确保仅使用查询中的人员:

ref.once("value", function(snapshot){
    var people = [];
    snapshot.forEach(function(data){
        people.push(data.val());
    });
    this.setState({
        people: people
    })

这还确保您仅调用 setState() 一次(每次身份验证状态更改时),这将稍微提高性能。

关于javascript - React firebase 在第一次加载时会重复数据,但在刷新时加载时不会重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42936703/

相关文章:

reactjs - 如何在 React Native 中更改 Google Places 自动完成组件上的占位符文本?

javascript - react 闪存消息 : How to make the message show without refreshing the page but refresh on 200

reactjs - 从 useEffect() Hook 调用时,layoutAnimation 不起作用

javascript - Firebase:TypeError:无法读取未定义的属性(读取 'getIdToken')

android - 如何检测 Firebase 中停止监听的客户端?

华为设备上的 Firebase 远程配置/实时数据库

php - 根据其值设置复选框

javascript - 找不到变量 : _ when using jasmine to test AngularJS service

javascript - jQuery 通过 1 次调用重新加载多个数据表

javascript - MDN 文档 : "How to convert an overlay extension to restartless" 中关于弄清楚 XUL 元素的段落意味着什么