[英]How to do setState inside callback: ReactJS
以下是我用來設置狀態的代碼。
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
,因為它始終未定義。
我試過:
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
,仍然沒有運氣。
我該如何解決這個問題?
您需要使用回調方法綁定正確的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
,如下所示:
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(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 的回答是正確的。或者你可以使用https://www.npmjs.com/package/core-decorators
並在函數前使用@autobind 裝飾器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.