Redux 中间件逻辑

Redux middleware logic

我很难理解 redux 中间件以及它在 Redux 存储中的确切配置方式。比如我有下面的例子

const store = compose(
  resetRedux('LOGOUT_USER'),
  applyMiddleware(...middlewares),
)(createStore)(rootReducer, initialState);

resetRedux 是一个中间件,它在调度字符串 LOGOUT_USER 时基本上重置整个 redux 存储。这很好用,但是,如果我将 console.log 放在 resetRedux 中间件中,它只会被调用一次,这很奇怪,考虑到我认为每次都需要检查操作以便能够决定是否重置商店。

export default function resetMiddleware(types = ['RESET']) {
  return (next) => (reducer, initialState) => {
    const resetTypes = Array.isArray(types) ? types : [types];
    console.log('THIS IS ONLY CALLED ONCE??!')
    const enhanceReducer = (state, action) => {
      if (~resetTypes.indexOf(action.type)) {
        state = undefined;
      }
      return reducer(state, action);
    };
    return next(enhanceReducer, initialState);
  }
};

所以,我很好奇当 console.log 只被调用一次时它是如何工作的。

这就是 compose 所做的,它获取您传递的函数并创建一个 "compose" 它们的新函数。

Arguments

(arguments): The functions to compose. Each function is expected to accept a single parameter. Its return value will be provided as an argument to the function standing to the left, and so on. The exception is the right-most argument which can accept multiple parameters, as it will provide the signature for the resulting composed function. Returns

Returns (Function): The final function obtained by composing the given functions from right to left.

可以查看源码here

它是函数式编程中的典型实用程序,例如lodash 也 provide it, underscore as well

您混淆了 "middleware" 和 "store enhancers"。您编写的 resetRedux 部分实际上是 "store enhancer",而不是中间件。

一个真正的中间件会为每个被分派的动作执行其主体。在创建商店时,商店增强器本身是 evaluated/executed 一次。您返回的 reducer 将针对每个操作执行,因为您正在创建一个函数来包装提供给 createStore 的任何 "real" reducer .

作为附录,我的 React/Redux 链接列表的 Redux Tutorials#Implementation Walkthroughs 部分有几篇文章解释了中间件如何在 Redux 中工作。