RemotePushIOS接收的令牌不能设置为状态
我正在使用RemotePushIOS获取设备令牌RemotePushIOS接收的令牌不能设置为状态,ios,react-native,state,Ios,React Native,State,我正在使用RemotePushIOS获取设备令牌 RemotePushIOS.requestPermissions(function(err, data) { if (err) { console.log("Could not register for push"); } else { console.log(data.token); var value = "v"+data.token; console.log(
RemotePushIOS.requestPermissions(function(err, data) {
if (err) {
console.log("Could not register for push");
} else {
console.log(data.token);
var value = "v"+data.token;
console.log("VALUE: " + value);
this.setState({
deviceToken: value
});
}
});
console.log
打印令牌,但当使用令牌设置状态时,程序崩溃,出现以下错误
'undefined is not an object (evaluating 'this.setState')'
为什么会这样?解决方法是什么?问题是,您的此
引用没有指向您的组件
为了避免this
引用绑定到回调函数,可以使用ES6箭头函数而不是function关键字
替换
RemotePushIOS.requestPermissions(function(err, data) {
与
ES6 arrow函数是词汇范围的,因此函数中的this
将指向函数外部的上下文,假设您在组件的方法中执行此代码,则该上下文将指向您的组件。谢谢。这解决了问题。
RemotePushIOS.requestPermissions((err, data) => {