You need to bind correct this
(class context) with callback method, then only you will be able to access the class properties and methods.
Possible Solutions:
1- Use arrow function, like this:
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, (err, affected, value) => {
if(!err){
this.setState( { quiz : value});
}
});
event.preventDefault();
};
2- Or use .bind(this)
with callback method
, like this:
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
if(!err){
this.setState( { quiz : value});
}
}.bind(this));
event.preventDefault();
};
The way you are using will also work, save the reference of this
inside the handleAddNewQuiz
method, like this way:
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();
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…