How does middleware execute async actions?

 ̄綄美尐妖づ 提交于 2020-01-05 07:12:43

问题


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 });
        })
    }
}

回答1:


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.

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



来源:https://stackoverflow.com/questions/59487232/how-does-middleware-execute-async-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!