在此 react 组件中,我想在用户单击“显示”按钮时将数据渲染到屏幕上,但必须按两次按钮才能显示数据。
constructor(props) {
super(props);
this.state = {
people: [] // start with empty array of people
}
}
这是我的 displayData 函数:
displayData = () => {
const db = fire.database(); // database instance
const dbRef = db.ref(); // database reference
var newPeopleArray = []; // new array to push everyone from database into
dbRef.on('value', snapshot => {
snapshot.forEach(childSnapshot => { // for every child in the data snapshot
var key = childSnapshot.key; // in this case returns first name
var childData = childSnapshot.val();
var newPerson = { // create new person object to push into the array
name: key,
age: childData.Age,
lastName: childData.LastName
};
// console.log(newPerson);
newPeopleArray.push(newPerson);
});
});
// set state to the new array of people from the database
this.setState({
people: newPeopleArray
});
}
我的 render() 只是将状态中的每个人与其属性映射:
render() {
const stateToRender = this.state.people.map( person => // maps each person in the state to a row in the table
<div key={person.name}>
{person.name}
{person.lastName}
{p.age}
</div>
);
return (
<div className="container">
<h1>Home Page</h1>
<br />
<button className="btn btn-danger" onClick={this.displayData}>Display</button>
{stateToRender}
</div>
);
}
最佳答案
displayData = () => {
const db = fire.database(); // database instance
const dbRef = db.ref(); // database reference
var newPeopleArray = []; // new array to push everyone from database into
dbRef.on('value', snapshot => {
newPeopleArray = snapshot.map(childSnapshot => { // for every child in the data snapshot
var key = childSnapshot.key; // in this case returns first name
var childData = childSnapshot.val();
var newPerson = { // create new person object to push into the array
name: key,
age: childData.Age,
lastName: childData.LastName
};
return newPerson;
});
// set state to the new array of people from the database
this.setState({
...this.state,
people: newPeopleArray ? newPeopleArray : []
});
});
}
关于javascript - 我必须单击显示按钮两次才能将数据呈现到屏幕上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331201/