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()發生在渲染後()ComponenWillMount發生後出於某種原因迴應原生
有人可以解釋或使這項工作?我很沮喪。
我已經改變了代碼,因爲人們幫助我,但它仍然是給錯誤:
undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')
'.on()'是一個回調嗎? 「sortedHighscores」爲空數組的原因可能是因爲你需要在'.on()'回調中設置狀態。 'setState'也可以是異步的,它的第二個參數有狀態完成設置時的回調。 –