componentDidMount() {
const refi = database.ref("highscores");
// Pushing sorted data to highscoreArray.
refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
sortedHighscores = [];
snapshot.forEach(function(child) {
sortedHighscores.push({
"username" : child.val().username,
"score" : child.val().highscore
});
});
sortedHighscores.sort(function(a,b) {
return a.score - b.score;
});
this.setState({highscoreArray : sortedHighscores.reverse()});
});
console.log("highscore is:", this.state.highscoreArray);
}
我正在尝试从数据库获取数据并将其放入 highscoreArray 中。然后我尝试将其作为渲染中的文本。由于某种原因它是空的或为空。这意味着 componentWillMount() 在 render() 之后发生
有人可以解释或让这个工作吗?我很沮丧。
我已经更改了代码,因为人们帮助了我,但它仍然给出错误:
undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')
最佳答案
Data stored in a Firebase Realtime Database is retrieved by attaching an asynchronous listener to a database reference
根据documentation .
因此,在不知道结果之前,以下代码 this.state.highscoreArray[0]["score"].toString()
将返回错误。在显示结果之前,检查 highscoreArray
是否包含某些项目。
此外,检索数据并不是一个好的做法。看看React component lifecycle :
componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method
关于javascript - 由于某种原因在 native react 中渲染后发生 ComponentWillMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44893816/