gpt4 book ai didi

javascript - 为什么 Redux 中间件定义为三个箭头函数,而不是一个带有三个参数的函数?

转载 作者:行者123 更新时间:2023-12-04 09:36:10 26 4
gpt4 key购买 nike

我们为什么要做这个:

const middleware = store => next => action => { ... }
而不是更简单的东西
const middleware = (store, next, action) => { ... }
Redux 团队以这种方式设计中间件有什么优势吗?如果我们拆分中间件功能,我们可以利用一些功能吗?
在我自己的应用程序中,我定义了 simplerMiddleware()可以从第二种形式转换为第一种形式的函数,它似乎运行良好。
function simpleMiddleware(simpleMiddlewareFunction) {
return store => next => action => simpleMiddlewareFunction(store, next, action);
}
为什么是三个箭头函数?
注意:我不是在问什么是柯里化(Currying),或者为什么在函数式编程中存在柯里化(Currying),或者柯里化(Currying)的一般好处是什么; Redux 设计者选择这个签名而不是更简单的三参数函数有什么特别的原因吗?

最佳答案

这在 the Redux FAQ entry on "why does the middleware signature use currying?" 中有专门解决。 :

Redux middleware are written using a triply-nested function structure that looks like const middleware = storeAPI => next => action => {}, rather than a single function that looks like const middleware = (storeAPI, next, action) => {}. There's a few reasons for this.

One is that "currying" functions is a standard functional programming technique, and Redux was explicitly intended to use functional programming principles in its design. Another is that currying functions creates closures where you can declare variables that exist for the lifetime of the middleware (which could be considered a functional equivalent to instance variables that exist for the lifetime of a class instance). Finally, it's simply the approach that was chosen when Redux was initially designed.

The curried function signature of declaring middleware is deemed unnecessary by some, because both store and next are available when the applyMiddleware function is executed. This issue has been determined to not be worth introducing breaking changes, as there are now hundreds of middleware in the Redux ecosystem that rely on the existing middleware definition.

关于javascript - 为什么 Redux 中间件定义为三个箭头函数,而不是一个带有三个参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62577438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com