以下是我用来设置状态的代码。
handleAddNewQuiz(event){ this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){ if(!err){ this.setState( { quiz : value}); // ERROR: Cannot read property 'setState' of undefined } }); event.preventDefault(); };
即使成功创建了数据库,也无法调用this.state,因为它始终是未定义的。
this.state
我试过了:
self = this; handleAddNewQuiz(event){ this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){ if(!err){ self.setState( { quiz : value}); // ERROR: self.setState is not a function } }); event.preventDefault(); };
但是它仍然失败,尝试使用a = this和使用a.setState,仍然没有运气。
a = this
a.setState
我该如何解决?
您需要将正确的this(类上下文)与回调方法绑定在一起,然后只有您才能访问类的属性和方法。
this
可能的解决方案:
1- 使用 箭头功能 ,如下所示:
handleAddNewQuiz(event){ this.quiz = new Quiz(this.db, this.newQuizName, (err, affected, value) => { if(!err){ this.setState( { quiz : value}); } }); event.preventDefault(); };
2- 或.bind(this)与一起使用callback method,如下所示:
.bind(this)
callback method
handleAddNewQuiz(event){ this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){ if(!err){ this.setState( { quiz : value}); } }.bind(this)); event.preventDefault(); };
您使用的方式也将起作用,保存方法this内部的引用handleAddNewQuiz,如下所示:
handleAddNewQuiz
handleAddNewQuiz(event){ let self = this; //here save the reference of this this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){ if(!err){ self.setState( { quiz : value}); } }); event.preventDefault(); };