Where to dispatch multiple actions in redux?

前端 未结 7 1585
终归单人心
终归单人心 2021-01-31 08:10

I am using redux with connect and redux-thunk middleware and containers.

Currently when an user perform an action, example one click on a butto

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 08:55

    The action creator is the correct location for dispatching multiple actions. Although code like the following would work:

    function actionCreator(payload) {
        return dispatch => {
            dispatch(action1(payload))
            dispatch(action2(payload))
        }
    }
    

    I would highly recommend redux-thunk based action creators to always return a resolved Promise, so that such action creators can be part of another async call. So, the simplest update to the above would be:

    function actionCreator(payload) {
        return dispatch => {
            dispatch(action1(payload));
            dispatch(action2(payload));
            return Promise.resolve();
        }
    }
    

    It would then be possible to dispatch to the above with: actionCreator(payload).then(doAnotherAction(anotherPayload)) or the following, if we need to maintain order of calls: actionCreator(payload).then(() => doAnotherAction(anotherPayload))

    If you wish to 'future-proof' your action creator, so that it could handle calling both async and sync action creators, you could write it as:

    function actionCreator(payload) {
        return dispatch =>
            Promise.resolve(dispatch(action1(payload))).then(
            () => dispatch(action2(payload)));
    }
    

    And, if you like ES6 arrow notation the above can be defined as:

    const actionCreator = payload => dispatch =>
            Promise.resolve(dispatch(action1(payload))).then(
            () => dispatch(action2(payload)));
    

提交回复
热议问题