我怎样才能避免不是函数错误?

时间:2017-02-23 00:39:30

标签: javascript reactjs

我在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 个答案:

答案 0 :(得分:1)

'这'不会引用包含switch语句的函数内部的组件实例。

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

这是一篇很好的文章,介绍了处理this内部bind的更多方法:https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.gdmm0mob8

以下是有关import Foundation import UIKit class ViewControllerTwo: UIViewController { var tape = Array<String>() @IBOutlet weak var calcTape: UITextView! override func viewDidLoad() { super.viewDidLoad() calcTape.text = tape.joined(separator: "\r\n") let sel:Selector = #selector(self.appMovedToBackground) let notificationCentre = NotificationCenter.default notificationCentre.addObserver(self, selector: sel, name: NSNotification.Name.UIApplicationWillResignActive, object: nil) let defaults = UserDefaults.standard if let _:AnyObject = defaults.object(forKey: "savedStringKey") as AnyObject?{ calcTape.text = UserDefaults.standard.string(forKey: "savedStringKey") print("SAVED") } else { print("not saved") } } @IBAction func clearAll(_ sender: UIButton) { // if the tape is not empty... if (calcTape.text != ""){ // empty it (set to empty string) calcTape.text = "" let bundleIdentifier = Bundle.main.bundleIdentifier UserDefaults.standard.removePersistentDomain(forName: bundleIdentifier!) } else { // otherwise, it was already empty, so display a message let alert = UIAlertController(title: "Alert", message: "Nothing to clear", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func appMovedToBackground(){ print("App moved to background") let myText = calcTape.text UserDefaults.standard.set(myText, forKey: "savedStringKey") print("saved in bg") } } https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

的一些文档