Javascript 如何在回调中设置状态:ReactJS
下面是我用来设置状态的代码Javascript 如何在回调中设置状态:ReactJS,javascript,reactjs,Javascript,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
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尽管数据库创建成功,但我无法调用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
,仍然没有成功
如何解决此问题?您需要使用回调方法绑定正确的
此
(类上下文),然后只有您才能访问类属性和方法
可能的解决方案: 1-使用,如下所示:
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, (err, affected, value) => {
if(!err){
this.setState( { quiz : value});
}
});
event.preventDefault();
};
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
if(!err){
this.setState( { quiz : value});
}
}.bind(this));
event.preventDefault();
};
2-或使用回调方法绑定(this)
,如下所示:
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, (err, affected, value) => {
if(!err){
this.setState( { quiz : value});
}
});
event.preventDefault();
};
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
的引用保存在handleddnewquick
方法中,如下所示:
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();
};
马扬克的回答是正确的。。
或者,您可以使用
并在函数之前使用@autobind decorator。使用()=>{}而不是使用函数(){}。我宁愿选择1和2变量,因为不必要地使用一个或多个变量不是很好example@ddeadlink,我也喜欢第一和第二种方式,在第三种方式,我建议他如何在第三个变量中保存引用,就像他在提问中使用的一样。我完全理解你的意思,所以我投了赞成票)谢谢你的建议:)