首页 > 解决方案 > 使用 Redux 的异步等待似乎不起作用

问题描述

我正在尝试在我的 redux 中实现 Async/Await 功能,但它似乎不起作用。

Actions.js

export function getUserCart(token) {
  return async dispatch => {
    await axios
      .get(`${apiUrl}/user/cart`, {
        headers: { Authorization: `Bearer ${token}` }
      })
      .then(response => {
        dispatch({

        console.log(GET_USER_CART_SUCCESS);
          type: GET_USER_CART_SUCCESS,
          cart: response.data
        });
      })
      .catch(error => {
        dispatch({
          type: GET_USER_CART_FAILED,
          error: error.response.data
        });
      });
  };
}

减速器.js

case GET_USER_CART_SUCCESS:
      return {
        ...state,
        cart: action.cart,
        type: action.type
      };

组件.js

componentDidMount() {
    console.log("before");
    this.props.getUserCart(this.props.user.idToken);
    console.log("after");
  }

控制台返回:

before
after
GET_USER_CART_SUCCESS

但是,如果我这样做

async componentDidMount() {
    console.log("before");
    await this.props.getUserCart(this.props.user.idToken);
    console.log("after");
  }

它返回正确的输出:

before
GET_USER_CART_SUCCESS
after

我对在我的组件函数中添加 async 和 await 感到不舒服,也不应该这样。我的 actions.js 有什么遗漏吗?

标签: asynchronousasync-awaitreact-redux

解决方案


推荐阅读