【问题标题】:React Uncaught TypeError: this.setState is not a functionReact Uncaught TypeError:this.setState 不是函数
【发布时间】: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+ 中解决这个问题?

【问题讨论】:

标签: reactjs babeljs ecmascript-next


【解决方案1】:

问题是 this 没有引用 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))
}
};

CODEPEN

您可以使用数组来简化您的逻辑

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))
}
};

【讨论】:

  • 你也可以在没有self变量的情况下使用箭头函数来实现这一点
  • @thedude 是的,这也是另一种方式。
  • @Sulthan,也许不是,因为他在 forloop 中使用了 setTimeout 函数,如果他删除该函数,他很可能只能获得所有函数中的最后一个值,顺便说一下他的逻辑可以绝对按照您的建议进行简化。
  • @ShubhamKhatri 我的意思是function(i),我什至没有注意到里面还有另一个function() :) 你是对的。
  • @Sulthan,没问题,:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 2017-03-10
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多