react-native - undefined 不是对象(评估 '_this2.getInfoFromToken')
问题描述
我在这里的类组件中编写了两个函数
facebooklogin = () => {
console.log('fblogin');
LoginManager.logInWithPermissions(['email', 'public_profile']).then(
function (result) {
if (result.isCancelled) {
console.log('Login cancelled');
} else {
console.log(
'Login success with permissions: ' +
result.grantedPermissions.toString(),
);
AccessToken.getCurrentAccessToken().then(data => {
// console.log(data);
// console.log(data.accessToken.toString());
const accessToken = data.accessToken.toString();
this.getInfoFromToken(accessToken);
});
}
},
function (error) {
console.log('Login fail with error: ' + error);
},
);
};
getInfoFromToken = token => {
console.log(token);
},
当我调用 facebooklogin() 时,它显示此错误可能未处理的 Promise Rejection (id: 4): TypeError: undefined is not an object (evaluating '_this2.getInfoFromToken')
解决方案
调用时this.getInfoFromToken(accessToken);
,您尝试this
从 a访问function
,在严格模式下等于undefined
。
您可以尝试将其设置为箭头函数,这将使内部this
引用适用于 contextual this
,这似乎是上面代码中的目的。
您只需要更改第 4 行:
function (result) {
对于箭头函数声明:
(result) => {
它行得通吗?
此外,您可能希望向 Promise 链添加一个.catch()
回调AccessToken.getCurrentAccessToken()
(如果它返回一个类似 Promise 的对象,看起来如此)。
推荐阅读
- python - 如何获取不和谐服务器中所有成员的列表?
- javascript - Calculating Time Difference with Current time
- javascript - 光滑的 JS 自定义导航不起作用
- python - 如何将数值与熊猫列标题中的分类范围进行比较?
- python - 具有固定数量元素的 Python 背包问题
- android - Android房间继承策略单表
- react-native - URL 不适合 React Native 中的移动屏幕
- javascript - 是否可以使用 XMLHttpRequest/FormData 对标准 ASP.Net Web 表单进行 HTTP POST?
- django - django运行错误可能是什么问题
- spring-mvc - 创建健康检查 API