问题描述
以下是我用来设置状态的代码.
Following is the code that I used to set the state.
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
,因为它总是未定义的.
Rven though the database is created successfully, I cannot call this.state
, as it's always undefined.
我试过了:
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
,还是不行.
But it still fails, tried with a = this
, and use a.setState
, still no luck.
我该如何解决这个问题?
How can I solve this?
推荐答案
您需要使用回调方法绑定正确的this
(类上下文),然后只有您才能访问类属性和方法.
You need to bind correct this
(class context) with callback method, then only you will be able to access the class properties and methods.
可能的解决方案:
1- 使用 箭头函数,像这样:
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- 或者使用 .bind(this)
和 回调方法
,像这样:
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();
};
你用的方法也行,把this
的引用保存在handleAddNewQuiz
方法里面,像这样:
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();
};
这篇关于如何在回调中执行 setState:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!