我正在创建一个在提取数据后填充数据的表。问题是,在第一次渲染时,数据是重复的,因此表行也有重复项,但当重新加载页面时,数据不再重复。为什么我的数据在第一次加载时会 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/