React Uncaught TypeError: this.setState is not a function
React Uncaught TypeError: this.setState is not a function
我正在使用 属性 初始值设定项。这是我的状态。
state = {
status: 'Simon Says!',
compArr: [],
color: 'red',
userArr: []
};
这是我的pen。
我这里叫状态
game = (event) => {
let compArr = this.state.compArr;
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
switch (compArr[i]) {
case 1:
this.setState({
color: 'green'
});
break;
case 2:
this.setState({
color: 'red'
});
break;
case 3:
this.setState({
color: 'yellow'
});
break;
case 4:
this.setState({
color: 'blue'
});
break;
}
}, 1000 * i);
}(i))
}
};
我收到以下错误
Uncaught TypeError: this.setState is not a function
如何在 ES2015+ 中解决这个问题?
问题是这并没有在setTimeout函数中引用正确的上下文,你可以按照下面的方式来做
game = (event) => {
var self = this;
let compArr = this.state.compArr;
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
switch (compArr[i]) {
case 1:
self.setState({
color: 'green'
});
break;
case 2:
self.setState({
color: 'red'
});
break;
case 3:
self.setState({
color: 'yellow'
});
break;
case 4:
self.setState({
color: 'blue'
});
break;
}
}, 1000 * i);
}(i))
}
};
您可以使用数组来简化您的逻辑
game = (event) => {
var self = this;
let compArr = this.state.compArr;
var color = ["green", "red", "yellow", "blue"];
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
self.setState({color: color[compArr[i] - 1]});
}, 1000 * i);
}(i))
}
};
我正在使用 属性 初始值设定项。这是我的状态。
state = {
status: 'Simon Says!',
compArr: [],
color: 'red',
userArr: []
};
这是我的pen。
我这里叫状态
game = (event) => {
let compArr = this.state.compArr;
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
switch (compArr[i]) {
case 1:
this.setState({
color: 'green'
});
break;
case 2:
this.setState({
color: 'red'
});
break;
case 3:
this.setState({
color: 'yellow'
});
break;
case 4:
this.setState({
color: 'blue'
});
break;
}
}, 1000 * i);
}(i))
}
};
我收到以下错误
Uncaught TypeError: this.setState is not a function
如何在 ES2015+ 中解决这个问题?
问题是这并没有在setTimeout函数中引用正确的上下文,你可以按照下面的方式来做
game = (event) => {
var self = this;
let compArr = this.state.compArr;
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
switch (compArr[i]) {
case 1:
self.setState({
color: 'green'
});
break;
case 2:
self.setState({
color: 'red'
});
break;
case 3:
self.setState({
color: 'yellow'
});
break;
case 4:
self.setState({
color: 'blue'
});
break;
}
}, 1000 * i);
}(i))
}
};
您可以使用数组来简化您的逻辑
game = (event) => {
var self = this;
let compArr = this.state.compArr;
var color = ["green", "red", "yellow", "blue"];
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
self.setState({color: color[compArr[i] - 1]});
}, 1000 * i);
}(i))
}
};