How to dispatch multiple actions one after another

2020-05-25 11:50发布

问题:

In my react / redux application I often want to dispatch multiple actions after another.

Given the following example: After a successful login I want to store the user data and after that I want to initiate another async action that loads application configuration from the server.

I know that I can use redux-thunkto build an action creator like this

function loginRequestSuccess(data) {
  return function(dispatch) {
    dispatch(saveUserData(data.user))
    dispatch(loadConfig())
  }
}

So my questions are:

  1. When the first dispatchreturns, is the state already changed by all reducers listening for that action? I'm wondering if the two dispatch calls are run strictly sequential.
  2. Is this approach considered best practice for dispatching multiple actions? If not, what would you suggest alternatively?

Thanks for any help!

回答1:

Yes redux-thunk allows you to do as you say, and yes it is a best practice for dispatching multiple actions (one that I prefer over the alternatives because of it's simplicity). The state is indeed updated as soon as you dispatch (by the time it returns), which is why you are given a function to retrieve the state in a thunk, instead of simply a reference to the state. In that way you can alter the state with one dispatch, and then call getState() to get a reference to the new state to read from if you need to.



回答2:

redux-thunk is exactly what you are looking for. I consider it very good practice.

To answer your question, indeed when the first dispatch returns the state is already changed by the called reducers.



回答3:

I know its a late response :-P You can do this by using Redux-Thunk and also checkout Redux-Saga. Redux Saga provides an amazing way to handle loads of actions at the same time. Below is an example of dispatching multiple actions using Redux-Thunk

function getAndLoadSider(moduleName){
    return function(dispatch){
        return doSomeApiCall(someData).then(function(item){
            let _item = someOtherFunction(item.collections);
                let _menuData = {
                    name: item.name,
                    key: item.key
                };
            return new Promise(function(res, rej){
                dispatch(actionOne(_menuData));
                res(_item);
            }).then((_item) =>  dispatch(actionTwo(_item)))
    }
}

Above method works well for your case when one action is dependent on the first. This is a promise based approach. If you don't like to do a lots of Promise coding I recommend you go for Sagas. Check out this link https://redux-saga.js.org/docs/advanced/ComposingSagas.html where you will learn how to compose sagas. Learning curve is steep; but once you are done, Sagas will make you a ninja redux dev.

Hope this helps :-)



标签: reactjs redux