asynchronous - 使用 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 有什么遗漏吗?
解决方案
推荐阅读
- angular - FormArray 动态下拉列表数据未正确加载
- html - 如何避免 Bootstrap 选项卡的 URL 哈希?
- bash - Bash:scp 由于变量名中的“(”字符而失败
- javascript - 如何通过 Gson 在 json 中创建 javascript 函数?
- c - 有没有办法用gdb用相对路径做fopen?
- postgresql - Cloud SQL(postgres)外部数据包装器连接超时到副本实例
- c - 为什么这段代码在 C 中没有返回任何内容
- reactjs - React 模态提交表单
- reactjs - React 中的可重用文本字段
- c++ - 如何使用 C++ 正则表达式在方括号之间查找字符