在成功回调中调用yield put()

5 yield reactjs amazon-cognito redux redux-saga

我是React和Redux的新手.

我正在使用react-redux来调用AWS Cognito服务,该服务接受包含成功和失败回调的对象.当我在成功回调中的console.log中时,我从AWS Cognito返回了我的JWT; 但是,我怎么能yield put()在这个回调中,因为它不是一个生成器函数(function*).

这是一些代码:

export function* getAWSToken(){
  // username, password and userPool come from react state
  // not showing code for brevity.

  const userData = {
      Username: username,
      Pool: userPool,
    };
  const authenticationData = {
    Username : username,
    Password : password,
  };

  const cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
  const authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

  // This here is the callback
  cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess(result){
      yield put(cognitoTokenObtained(result.getIdToken().getJwtToken())
    },
    onFailure(err){}
  });
}
Run Code Online (Sandbox Code Playgroud)

The*_*sor 3

如果您使用的是 redux-saga (非常棒),您可以使用调用效果将 asyc 回调(如 cognitoUser.authenticateUser)转换为一组由中间位置执行的指令。

当中间件解析调用时,它将通过生成器进入下一个yield语句,您可以将返回结果分配给一个变量,然后可以使用put效果将其放置在您的状态中。

export function* getAWSToken(){
  // username, password and userPool come from react state
  // not showing code for brevity.

  const userData = {
      Username: username,
      Pool: userPool,
    };
  const authenticationData = {
    Username : username,
    Password : password,
  };

  const cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
  const authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

  // Note: since you're invoking an object method
  // you'll want to pass the object's context (this) with the call via an array

  const token = yield apply(cognitoUser, cognitoUser.authenticateUser, [authenticationDetails, { onSuccess(response){return response}, onFailure(){} }]);

  yield put(cognitoTokenObtained(token.getIdToken().getJwtToken());
}
Run Code Online (Sandbox Code Playgroud)

还有这个令人难以置信的教程我强烈推荐

编辑:为了简洁起见,您省略了一些代码,但我强烈建议将代码包装在 try catch 中的生成器内,因为您依赖于来自 API 的外部 IO。