我正在尝试从Firebase获取有序数据并将其设置为状态highscoreArray,但它给出错误“undefined不是函数(评估'this.setState({highscoreArray:sortedHighscores})')
componentDidMount() {
const reference = database.ref("highscores");
// Pushing sorted data to highscoreArray.
reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
sortedHighscores = [];
snapshot.forEach(function (child) {
sortedHighscores.push({
"username": child.val().username,
"score": child.val().highscore
});
});
sortedHighscores = sortedHighscores.reverse();
console.log("sortedh", sortedHighscores); // fetch success
this.setState({highscoreArray: sortedHighscores}); // gives error
});
}
答案 0 :(得分:4)
箭头功能的一个主要优点是它没有自己的这个值。这是词汇绑定到封闭范围。
class Logger {
dumpData(data) {
var _this = this;
// this dumps data to a file and get the name of the file via a callback
dump(data, function (outputFile) {
_this.latestLog = outputFile;
});
}
}
//使用箭头功能
class Logger {
dumpData(data) {
dump(data, outputFile => this.latestLog = outputFile);
}
}
答案 1 :(得分:1)
1.这在循环内无法访问,因此在此函数中的任何地方使用变量let that = this
使用that
。
componentDidMount() {
const reference = database.ref("highscores");
let that = this // here your variable declaration
// Pushing sorted data to highscoreArray.
reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
sortedHighscores = [];
snapshot.forEach(function (child) {
sortedHighscores.push({
"username": child.val().username,
"score": child.val().highscore
});
});
sortedHighscores = sortedHighscores.reverse();
console.log("sortedh", sortedHighscores); // fetch success
that.setState({highscoreArray: sortedHighscores}); // gives error
});
}
希望这会帮助你:)快乐的编码!
答案 2 :(得分:0)
在function
回调中,this
具有不同的上下文。使用箭头功能,或在外面存储引用:
箭头:
reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... });