Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
RemotePushIOS接收的令牌不能设置为状态_Ios_React Native_State - Fatal编程技术网

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获取设备令牌

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) => {