【发布时间】:2017-09-11 12:55:29
【问题描述】:
我正在使用属性初始化器。这是我的状态。
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))
}
};
我收到以下错误
未捕获的类型错误:this.setState 不是函数
如何在 ES2015+ 中解决这个问题?
【问题讨论】:
-
定义
const colors = ['green', 'red', 'blue', 'yellow'];并调用this.setState({color: colors[compArr[i] - 1]})。不需要包装函数。 -
ES7 去年发布。您正在谈论一个实验性功能。
标签: reactjs babeljs ecmascript-next