gpt4 book ai didi

javascript - 我必须按两次按钮才能从 firebase 实时数据库填充 react 状态

转载 作者:行者123 更新时间:2023-11-28 14:24:59 25 4
gpt4 key购买 nike

在我的 react 组件中,当组件安装时,我想运行 loadData() 函数来填充状态中的人员对象数组。

该组件称为 UserDisplaySection.js

componentDidMount() {
this.loadData();
}

其中调用函数加载数据:

loadData = () => {
const db = fire.database();
const ref = db.ref('User');

let currentState = this.state.people;
ref.on('value', (snapshot) => {
snapshot.forEach( (data) => {
const currentStudent = data.val();
let user ={
"email" : currentStudent.Email,
"name": currentStudent.Name,
"age": currentStudent.Age,
"location": currentStudent.Location,
"course": currentStudent.Course,
"interests": currentStudent.Interests
}
currentState.push(user);

});
});

this.setState({
people: currentState
});

}

从另一个名为 Home.js 的组件中,我使用按钮切换来渲染 UserDisplaySection.js,该按钮设置名为 willDisplayUser 的 bool 值的状态,该 bool 值默认初始化为 false。

handleDisplayUsers = e => {
e.preventDefault();
this.setState({
willDisplayUsers: !(this.state.willDisplayUsers),

});
}

render() {
return (
<div>
<button className="mainButtons" onClick={this.handleDisplayUsers}>View Users</button> <br />
{this.state.willDisplayUsers ? <UserDisplaySection/>: null}

</div>
);

}

注意:该函数可以工作并使用正确的数据填充状态,但只有在我第二次渲染 UserDisplaySection.js 组件之后,并且在重新加载页面之前才能完美工作。

最佳答案

通过执行ref.on(),您实际上是在声明一个“监听特定位置的数据更改”的监听器,如 doc 中所述。 。 “回调将针对初始数据触发,并在数据发生变化时再次触发”。换句话说,它与按钮 onClick 事件断开连接。

如果您想按需获取数据,即单击按钮时,您应该使用 once()方法,它“监听指定事件类型的一个事件,然后停止监听”。

关于javascript - 我必须按两次按钮才能从 firebase 实时数据库填充 react 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53726889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com