如何将Firebase数据实时更新到React应用程序 [英] How to update Firebase data to the React application in realtime
本文介绍了如何将Firebase数据实时更新到React应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个将Firebase数据实时更新为React的应用程序.我想做的是让一个用户更新应用程序中的状态,同时应为另一个用户更新状态.
I'm developing an application that updates Firebase data in realtime to React. What I want to do is that a user updates the state in the app, at the same time it should be updated for another user.
我已经完成了构建,但是它会不断渲染 renderStatus()
,而且速度太慢.我想在RDB数据更新后对其进行更新.
I have built it done but it continually renders renderStatus()
and it's too slow. I want to make it updated once RDB data updated.
class Status extends Component {
constructor(props) {
super(props);
this.state = {
to_status: false,
from_status: false
};
}
// change the state in RDB
handleSatus = () => {
const { post } = this.props;
firebase
.database()
.ref("/busy/" + post.uid)
.set({
status: true,
last_changed: firebase.database.ServerValue.TIMESTAMP
});
this.setState({ to_status: true });
};
renderStatus() {
const { post } = this.props;
const { to_status, from_status } = this.state;
// fetch the data in RDB
let self = this;
firebase
.database()
.ref("/busy/" + post.uid)
.once("value")
.then(function(snapshot) {
self.setState({ from_status: snapshot.val().status });
});
if (this.state.from_status) {
return (
<p>Updated</p>
);
} else {
return (
<p>Not updated yet</p>
);
}
}
render() {
return (
<div>
{this.renderStatus()}
<button onClick={this.handleStatus()}>Click!</button>
</div>
)
}
推荐答案
您通常需要:
- 在您的
componentDidMount()
方法中注册一个on()
侦听器. - 使用数据库中的相关数据,初始加载时间和更改时间,调用
setState
. - 让React照常处理来自状态的渲染.
- Register an
on()
listener in yourcomponentDidMount()
method. - Call
setState
with the relevant data from the database, when that initially loads and when it changes. - Let react handle the rendering from the state as usual.
所以像这样:
componentDidMount() {
firebase
.database()
.ref("/busy/" + posy.uid)
.on("value")
.then((snapshot) => {
this.setState({ from_status: snapshot.val().status });
});
}
render() {
return (
<div>
<p>{this.state.from_status?"Updated":"Not updated yet"}</p>
<button onClick={this.handleStatus()}>Click!</button>
</div>
)
}
这篇关于如何将Firebase数据实时更新到React应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文