2017-02-23 99 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。是的,你顯然是對的。 –