使用 redux store 的 dispatch 实例与传入 dispatch 作为参数

using redux store's instance of dispatch vs. passing in dispatch as parameter

docs 中,Dan 没有给出太多关于改变 dispatch 传递到中间件的方式的理由。他只是这样说:

But there's also a different way to enable chaining. The middleware could accept the next() dispatch function as a parameter instead of reading it from the store instance.

这是什么原因?对我来说,现在 applyMiddleware 中的代码将采用存储和分派的 2 个参数,而不只是单独存储,这看起来更奇怪了。

长得怪不是问题

const logger = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result
}

请注意,函数式语言默认采用这种格式,这是完全正常的。

这样做的原因是猴子补丁尚未确立为推荐的编程方法。将 next 传递给函数更加灵活,并且不需要调用任何函数(开发人员的函数),从而减轻开发人员的负担并降低出错的可能性。

最后,Dan 喜欢解释他为什么要以某种方式编写代码,但作为 lib 用户,我们这些低级开发人员不是决策者。 decision has already been made 这就是在 Redux 中使用中间件的方式。你总是可以 fork Redux 并根据自己的喜好修改它,但请注意,Redux 的力量不是 lib 中的代码,而是第三方开发人员附加到它的代码。如果不配合,你就会放弃所有的力量。

这是一个非常常见的问题,我很快就会将其添加到 Redux 常见问题解答中。

简而言之,Redux 深受函数式编程原则的影响,柯里化是 Dan 和 Andrew 在进行初始设计时碰巧采用的方法。一旦选择了它,它基本上就保持这种兼容性。

最初的设计在 Redux issue #55, and Dan proposed a rewrite and then rejected his own proposal in issue #1744 中进行了讨论。