与Redux异步等待似乎不起作用

问题描述 投票:0回答:1

我正在尝试在我的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
        });
      });
  };
}

Reducers.js

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

Component.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

我不喜欢在组件的函数中添加异步和等待,也不应该那样。我的actions.js中缺少什么吗?

asynchronous async-await react-redux
1个回答
0
投票

https://redux.js.org/advanced/async-actions我相信您需要笨拙的中间件来为您处理异步。

© www.soinside.com 2019 - 2024. All rights reserved.