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

Call yield put() inside a success callback

我是 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){}
  });
}

如果您使用的是 redux-saga(非常棒),您可以使用 call effect 将像 cognitoUser.authenticateUser 这样的异步回调转换为一组由 middlewhere 执行的指令.

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

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());
}

还有 this incredible tutorial 我强烈推荐。

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