[英]How to do setState inside callback: ReactJS
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();
};
Rven though the database is created successfully, I cannot call this.state
, as it's always undefined.尽管数据库已成功创建,但我无法调用this.state
,因为它始终未定义。
I tried:我试过:
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();
};
But it still fails, tried with a = this
, and use a.setState
, still no luck.但它仍然失败,尝试使用a = this
,并使用a.setState
,仍然没有运气。
How can I solve 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.您需要使用回调方法绑定正确的this
(类上下文),然后只有您才能访问类属性和方法。
Possible Solutions:可能的解决方案:
1- Use arrow function , like this: 1-使用箭头功能,像这样:
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: 2-或者将.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();
};
The way you are using will also work, save the reference of this
inside the handleAddNewQuiz
method, like this way:您使用的方式也可以使用,将this
的引用保存在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();
};
Mayank's answer is correct.. Alternatively you can use https://www.npmjs.com/package/core-decorators Mayank 的回答是正确的。或者你可以使用https://www.npmjs.com/package/core-decorators
and use the @autobind decorator before the function.并在函数前使用@autobind 装饰器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.