如何在AWS Cognito userhandler的onSuccess回调中设置React状态?
问题根因
onSuccess回调使用传统function声明时,函数自身的this绑定会脱离React类组件实例的上下文,因此无法访问this.setState方法。
原代码同时存在两处语法问题:
- 构造函数内的state对象字面量中,键值对分隔符误用分号,会触发运行时报错
- 登录触发方法
hanleSignIn存在拼写错误
修正方案
将回调的传统函数声明替换为箭头函数,箭头函数无独立this绑定,会继承外层词法作用域的组件实例引用,即可正常调用setState更新状态。
修正后的可运行代码:
import { CognitoAuth } from 'amazon-cognito-auth-js' class A extends Component { constructor(props) { super(props); this.state = { auth: "", token: "", login: false } } handleSignIn = () => { const auth = this.initCognitoSDK(); const curUrl = window.location.href; auth.parseCognitoWebResponse(curUrl); auth.getSession(); } initCognitoSDK = () => { const authData = { ClientId: '你的客户端ID', AppWebDomain: 'https://你的Cognito域名', TokenScopesArray: ['openid','email','phone'], RedirectUriSignIn: 'http://localhost:3000', RedirectUriSignOut: 'http://localhost:3000', IdentityProvider: '你的身份提供商配置', UserPoolId: '你的用户池ID', AdvancedSecurityDataCollectionFlag: false }; const auth = new CognitoAuth(authData); auth.userhandler = { onSuccess: (result) => { if(result) { const idToken = result.getIdToken().getJwtToken(); this.setState({ auth: auth, token: idToken, login: true }) } }, onFailure: (err) => { console.log("Error!" + err); } }; auth.useCodeGrantFlow(); return auth; } }
其他可选实现方式
如果不使用箭头函数,可在SDK初始化逻辑开头通过闭包缓存组件实例引用,回调内使用缓存的引用调用setState:
initCognitoSDK = () => { // 缓存组件实例this const componentInstance = this // 其他初始化逻辑... auth.userhandler = { onSuccess: function(result) { componentInstance.setState({ auth: componentInstance, token: result.getIdToken().getJwtToken(), login: true }) } } }
内容的提问来源于stack exchange,提问作者LiLian
相关产品推荐
相关产品推荐

