gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:37:19 25 4
gpt4 key购买 nike

我是 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 这样的异步回调转换为一组由中间位置执行的指令。

当中间件解析调用时,它将逐步通过生成器到下一个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。

关于reactjs - 在成功回调中调用yield put(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38708583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com