2017-03-21 59 views
0

我正在創建一個在提取數據後填充數據的表。問題是,在第一次渲染時,數據被複制,因此表格行也有重複,但是當頁面重新加載時,數據不再被複制。爲什麼我的數據在第一次加載時自我複製,而後又沒有加載?React firebase在第一次加載時複製數據,但在刷新時加載時沒有重複

這裏是我的代碼:

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; 

後看到的第一個頁面加載控制檯日誌複製,但沒有任何負載先謝謝你!

回答

1

onAuthStateChanged事件可能會多次觸發。每次它都會增加更多的人到顯示器上。

爲了解決這個問題,請確保您只需使用人查詢:

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

這也確保您撥打setState()只有一次(每次的AUTH狀態變化),這將提高性能位。

+0

謝謝弗蘭克!這完美的作品! – meherrr

+0

好聽。如果我的回答很有用,請點擊左側的upvote按鈕。如果它回答了您的問題,請點擊複選標記以接受它。這樣別人就知道你已經(充分)幫助了。 –

相關問題