Reactjs 为什么此setState不是ComponendImount中的函数?
我试图从Firebase获取有序数据并将其设置为状态highscoreArray,但它给出错误“undefined不是函数(计算'this.setState({highscoreArray:sortedHighscores}')”Reactjs 为什么此setState不是ComponendImount中的函数?,reactjs,firebase,react-native,Reactjs,Firebase,React Native,我试图从Firebase获取有序数据并将其设置为状态highscoreArray,但它给出错误“undefined不是函数(计算'this.setState({highscoreArray:sortedHighscores}')” 在函数回调中,此具有不同的上下文。可以使用箭头函数,也可以在外部存储引用: 箭头: reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... }); 在
在
函数
回调中,此
具有不同的上下文。可以使用箭头函数,也可以在外部存储引用:
箭头:
reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... });
在
函数
回调中,此
具有不同的上下文。可以使用箭头函数,也可以在外部存储引用:
箭头:
reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... });
arrow函数的一个主要优点是它没有自己的this值。它的this在词汇上绑定到封闭范围
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);
}
}
arrow函数的一个主要优点是它没有自己的this值。它的this在词汇上绑定到封闭范围
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.这在循环中是不可访问的,因此在函数中需要的任何地方使用变量
让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
});
}
希望这将帮助您:)快乐编码!1。这在循环中不可访问,因此请使用变量
let that=this
the使用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
});
}
希望这能帮助你:)快乐编码!
这不是你想象的。使用箭头函数。这不是你想象的。使用箭头函数。