如何异步/等待redux-thunk操作? [英] how to async/await redux-thunk actions?

查看:133
本文介绍了如何异步/等待redux-thunk操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

action.js

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:

Possible Unhandled Promise Rejection (id: 0): undefined is not a function (evaluating '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()时,一切工作都很好.我怀疑异步/等待实现中缺少某些内容.试图找出答案.

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

从Medium帖子中以异步/等待方式引用Redux来引用: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆