zoukankan      html  css  js  c++  java
  • [React + Functional Programming ADT] Create Redux Middleware to Dispatch Multiple Actions

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

  • 相关阅读:
    [华为]字符串反转
    [华为]字符个数统计
    [华为]字符串分隔
    [华为]计算字符个数
    [华为]字符串最后一个单词的长度
    感悟-思考-生活
    [百度校招]打印全排列
    [阿里]逆序打印整数,要求递归实现
    [百度]数组中去掉连续重复的数字,只保留1个
    百度NLP三面
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10363068.html
Copyright © 2011-2022 走看看