如何从Firebase实时更新状态? | react.js

问题描述:

我有一个html元素,每次Firebase发生更改时都需要更新.到目前为止,我要做的是实现此特定功能:

I have an html element that needs to updated every time there is a change in Firebase. What I've done so far is this implement this particular function:

componentWillMount() {
    var that = this;
    var updateDb = firebase.database().ref("currentToken");
    updateDb.on("value", function(snapshot) {
        that.setState({ currentToken: snapshot.val() });
    });
    console.log(that.state.currentToken);
    document.getElementById("tokenField").innerHTML = "Current Token: " + that.state.currentToken;
}

每当Firebase发生变化时,更新应用程序中变量的正确方法是什么?请提出任何建议,以提高我的编码水平,因为我是一个初学者.

What is the proper way to update a variable in my app whenever there is a change in Firebase? Kindly give any suggestion to improve my coding as I'm a beginner.

对我来说最突出的一件事是您如何处理this.您应该能够使用箭头功能保持范围:

One thing that stands out to me is how you're handling this. You should be able to use a arrow function to maintain scope:

updateDb.on("value", (snapshot) => {
  this.setState({ currentToken: snapshot.val() });
});

与众不同的另一件事是

document.getElementById("tokenField").innerHTML =
  "Current Token: " + that.state.currentToken;

当您调用setState时,React不会更新该元素. React将通过调用render方法来更新所有需要state的组件.我不知道其余代码的样子,但是假设这是您要渲染的组件,则应在render中像这样更新它:

React will not update that element when you call setState. React will update any components requiring state by calling the render method. I don't know what the rest of your code looks like, but assuming that is a component that you are rendering, you should update it in render like this:

<div id="tokenField">
    Current token {this.state.currentToken}
</div>