我正在开发一个应用程序,可以实时更新Firebase数据以应对。我想做的是用户更新应用程序中的状态,同时应该为另一个用户更新状态。
我已经完成了它,但它不断渲染renderStatus()
而且速度太慢了。我想在RDB数据更新后对其进行更新。
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 像往常一样处理状态中的渲染。
所以像这样:
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>
)
}