[React + Functional Programming ADT] Create Redux Middleware to Dispatch Multiple Actions
React to create redux Programming multiple functional ADT
2023-09-14 08:59:15 时间
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的jsx和React.createElement是什么关系?面试常问
- React源码分析7-state计算流程和优先级
- React魔法堂:echarts-for-react源码略读
- react高频知识点梳理
- to program_I Just Want To
- 百度前端高频react面试题(持续更新中)_2023-02-27
- 使用react修改ant design默认样式|自定义
- 从react源码角度看React-Hydrate原理
- react hook开发遇到的一些问题
- React源码分析--hooks源码
- 在React中使用 react-router-dom 编程式路由导航【含V5.x、V6.x】
- react的jsx和React.createElement是什么关系?面试常问5
- React源码分析(一)Fiber_2023-02-14
- React源码解读之任务调度_2023-02-20
- react 基础之组件篇二——Style in React
- React 许可证虽严苛,但不必过度 react
- 探索React框架中MySQL数据库的应用(react mssql)