[英]I have to click the display button twice to render the data to the screen?
In this react component, I want to render the data to the screen when the 'Display' button is clicked by the user, but the button has to be pressed twice for the data to display. 在此React组件中,我想在用户单击“显示”按钮时将数据呈现到屏幕上,但是必须按下两次按钮才能显示数据。 Any Suggestions? 有什么建议么?
constructor(props) {
super(props);
this.state = {
people: [] // start with empty array of people
}
}
Here's my displayData function: 这是我的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
});
}
And my render() just maps each person in the state with their properties: 而且我的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>
);
}
Try this, hope this will work 试试这个,希望这能起作用
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 : []
});
});
}
dbRef.on
is asynchronous code, move the this.setState
code inside the callback of dbRef.on
. dbRef.on
是异步代码,移动this.setState
代码的回调内部dbRef.on
。
// set state to the new array of people from the database
this.setState({
people: newPeopleArray
});
The issue with your original code was execution of this.setState
before completion of async dbRef.on
与原代码的问题是执行this.setState
异步完成前dbRef.on
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.