中间件如何执行异步操作? [英] How does middleware execute async actions?
问题描述
我在理解 Redux-Thunk(或其他中间件)如何执行异步操作时有点困难.从下面的示例中,我可以看到当 onOrder
被调用时(可能是通过点击事件),它将调度由 purchaseBurger
创建的操作.purchaseBurger
依次返回一个函数,该函数将发送一个指示购买开始的动作,然后是一个 http 请求.我的困惑是:purchaseBurger
返回的那个函数什么时候真正被调用和执行?它也是如何被调用的?
I am having a little difficulty understanding how Redux-Thunk (or other middleware) execute async actions. From below example, I can see that when onOrder
is called (maybe via a click event), it will dispatch the action created by purchaseBurger
. purchaseBurger
in turn return a function that will dispatch an action indicating purchase started, followed by an http request. My confusion is: When does that function returned by purchaseBurger
actually gets called and executed? How does it get called too?
ContactData.js
const mapDispatchToProps = dispatch => {
return {
onOrder: (orderData) => dispatch(actions.purchaseBurger(orderData))
}
}
<小时>
orders.js
export const purchaseBurgerStart = (orderData) => {
return {
type: actionTypes.PURCHASE_BURGER_START
}
}
export const purchaseBurger = (orderData) => {
return dispatch => {
dispatch(purchaseBurgerStart());
axios.post('/orders.json', orderData)
.then(response => {
})
.catch(error => {
this.setState({ loading: false });
})
}
}
推荐答案
如果看一下redux-thunk 你会看到,当你调度一个动作时,它会检查这个动作是否是一个函数,如果是它就会调用传入的函数dispatch, getState, extraArgument
作为参数.
If you take a look at the source of redux-thunk you will see that when you dispatch an action it checks to see if the action is a function, and if it is it will invoke the function passing in dispatch, getState, extraArgument
as arguments.
因此,当您调用 dispatch(purchaseBurger())
时,它会将 purchaseBurger
返回的函数作为操作分派,然后中间件将检查类型并查看它是一个函数,将使用 dispatch
作为第一个参数来调用它
So when you call dispatch(purchaseBurger())
it will dispatch the returned function from purchaseBurger
as an action, the middleware will then check the type and see that it is a function and will call it with dispatch
as the first argument
这篇关于中间件如何执行异步操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!