使用 AWS Cognito 用户处理函数时如何设置状态

How to set state when using AWS Cognito userhandler function

我正在处理需要通过 AWS Cognito 授权的 React 项目。按照文档,我可以成功获取 ID 令牌。但是我不知道如何在 onsuccess 回调中更新状态,这是我的代码。感谢您的帮助。

    class A extends Component{
        constructor(){
             super();
             this.state = {
                 auth: "";
                 token: "";
                 login:false;
            }
        }
    }
    hanleSignIn = ()=>{
       let auth = this.initCognitoSDK();
        let curUrl = window.location.href;
        auth.parseCognitoWebResponse(curUrl);
        auth.getSession();
    }
    initCognitoSDK=()=>{
    let authData = {
        ClientId: // client id 
        AppWebDomain:  // "https://" part.
        TokenScopesArray:  // like ['openid','email','phone']...
        RedirectUriSignIn: 'http://localhost:3000',
        RedirectUriSignOut: 'http://localhost:3000',
        IdentityProvider: **,
        UserPoolId: **,
        AdvancedSecurityDataCollectionFlag: false  
    };
    let auth = new CognitoAuth(authData);
    auth.userhandler = {
        onSuccess: function (result) {
            if(result){
                let idToken = result.getIdToken().getJwtToken();
                //here I want to update the following state once get token successfully
                // However I can't reach this.setState in the callback function
                this.setState({
                    auth: auth,
                    token: idToken,
                    login: true
                })
            }
        },
        onFailure: function (err) {
            console.log("Error!" + err);
        }
    };
    auth.useCodeGrantFlow();
    return auth;
}

   

您正在为回调使用常规函数,这意味着当调用回调时,this 的上下文是 auth.userhandler,它没有 setState 属性.与代码的其他部分一样,您应该使用箭头函数表示法,以便它使用词法 this 这是您的组件实例:

auth.userhandler = {
  onSuccess: (result) => {
    ...
    this.setState({ ... });
  }
};