如何异步/等待 redux-thunk 操作? [英] how to async/await redux-thunk actions?
问题描述
action.js
export function getLoginStatus() {
return async(dispatch) => {
let token = await getOAuthToken();
let success = await verifyToken(token);
if (success == true) {
dispatch(loginStatus(success));
} else {
console.log("Success: False");
console.log("Token mismatch");
}
return success;
}
}
component.js
component.js
componentDidMount() {
this.props.dispatch(splashAction.getLoginStatus())
.then((success) => {
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
});
}
但是,当我像下面这样使用 async/await 编写 component.js 代码时,我收到此错误:
However, when I write component.js code with async/await like below I get this error:
可能未处理的承诺拒绝(id:0):未定义不是函数(评估'this.props.dispatch(splashAction.getLoginStatus())')
component.js
component.js
async componentDidMount() {
let success = await this.props.dispatch(splashAction.getLoginStatus());
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
}
我如何等待 getLoginStatus() 然后执行其余的语句?使用 .then() 时一切正常.我怀疑我的 async/await 实现中缺少某些东西.试图弄清楚这一点.
How do I await a getLoginStatus() and then execute the rest of the statements? Everything works quite well when using .then(). I doubt something is missing in my async/await implementation. trying to figure that out.
推荐答案
Promise 方法
export default function createUser(params) {
const request = axios.post('http://www...', params);
return (dispatch) => {
function onSuccess(success) {
dispatch({ type: CREATE_USER, payload: success });
return success;
}
function onError(error) {
dispatch({ type: ERROR_GENERATED, error });
return error;
}
request.then(success => onSuccess, error => onError);
};
}
异步/等待方法
export default function createUser(params) {
return async dispatch => {
function onSuccess(success) {
dispatch({ type: CREATE_USER, payload: success });
return success;
}
function onError(error) {
dispatch({ type: ERROR_GENERATED, error });
return error;
}
try {
const success = await axios.post('http://www...', params);
return onSuccess(success);
} catch (error) {
return onError(error);
}
}
}
引用自用 async/await 解释 Redux 的 Medium 帖子:https:///medium.com/@kkomaz/react-to-async-await-553c43f243e2
Referenced from the Medium post explaining Redux with async/await: https://medium.com/@kkomaz/react-to-async-await-553c43f243e2
这篇关于如何异步/等待 redux-thunk 操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!