How to dispatch multiple actions one after another

前端 未结 3 1744
借酒劲吻你
借酒劲吻你 2021-02-05 05:19

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 d

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 06:07

    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 :-)

提交回复
热议问题