2017-02-23 100 views
-1

我在ES6模式下的reactJs应用程序中使用了switch语句。我有这样的说法:如何避免不是功能错误?

switch (hoera) { 
     case 'one': 
      return this.runThis(); 
      break; 
     default: 
} 

runThis(something) 
{ 
     .. 
} 

的chromeconsole错误是:

TypeError: this.runThis is not a function 

所以runThis是我的组件上定义的方法。似乎在switchstatement以外的工作,虽然。

+1

为什么你不加'的console.log(此, .runThis)'所以你会发现它是什么。 – Malvolio

+0

您需要提供更多的上下文。但我想这是重复的[无法访问事件处理程序中的React实例(this)](http://stackoverflow.com/q/29577977/218196) –

回答

1

'this'不包含您的函数中包含switch语句的函数。

您可以在构造函数中添加this.myFunction = this.myFunction.bind(this)其中myFunction是包含switch语句的函数。

这里有更多的方式来处理this的反应中的好文章:https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.gdmm0mob8

这里是一些文档约bindhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

+0

我真的认为它不是'runThis'需要绑定,但具有开关的功能(未显示)。 –

+0

哦..你可能是对的! –

+0

@JoPeyper。是的,你显然是对的。 –