我是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){}
});
}
答案 0 :(得分:3)
如果您正在使用redux-saga(非常棒),您可以使用call effect将asyc回调(如cognitoUser.authenticateUser)转换为一组由midwhere执行的指令。
当中间件解析调用时,它将逐步通过生成器到下一个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());
}
还有this incredible tutorial我强烈推荐。
编辑:为简洁起见,您省略了一些代码,但我强烈建议在try catch中将代码包装在生成器中,因为您依赖于API中的外部IO。