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

本文介绍了一种在React应用程序中使用中间件处理批量Action分发的方法。通过创建一个特殊的中间件,可以将多个Action封装成数组进行一次性分发,简化了复杂状态更新的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()])

 

转载于:https://www.cnblogs.com/Answer1215/p/10363068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值