我正在尝试在我的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
我不喜欢在组件的函数中添加async和await,也不应该这样。我的actions.js中缺少什么吗?