首页 > 其他 > 详细

[React + Functional Programming ADT] Create Redux Middleware to Dispatch Multiple Actions

时间:2019-02-11 20:35:14      阅读:203      评论:0      收藏:0      [点我收藏+]

We only have a few dispatching functions that need to be known by our React Application. Each one actually has multiple actions that need to be dispatched. While we could just have many imperative calls to dispatch in our dispatching functions, but why not use it as an excuse to use an array and write some middleware.

We will create a middleware function that will check dispatched actions to see if they are arrays. If a given action is an array we loop over the array, dispatching each action in turn. If it is not however, we just pass it along to be handled downstream.

 

Create a middle which can take dispatch fns as array type:

function multiMiddleware({ dispatch }) {
  return next => action => {
    return isSameType(Array, action)
      ? action.forEach(a => dispatch(a))
      : next(action);
  };
}

 

Apply the middle:

import { createStore, compose, applyMiddleware } from "redux";
function multiMiddleware({ dispatch }) {
  return next => action => {
    return isSameType(Array, action)
      ? action.forEach(a => dispatch(a))
      : next(action);
  };
}

const middleware = applyMiddleware(multiMiddleware);
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export default createStore(
  reducer,
  initialState(),
  composeEnhancers(middleware)
);

 

Previously, we can only apply one dispatch fn:

start: () => dispatch(startGame())

 

Now we can dispatch multi actions:

start: () => dispatch([startGame(), hideAllCards()])

 

[React + Functional Programming ADT] Create Redux Middleware to Dispatch Multiple Actions

原文:https://www.cnblogs.com/Answer1215/p/10363068.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!