gpt4 book ai didi

redux - 理解 redux 中的 compose 函数

转载 作者:行者123 更新时间:2023-12-03 06:01:17 25 4
gpt4 key购买 nike

我试图在 redux 中创建一个商店,目前我正在使用以下语法:-

const middlewares = [
thunk,
logger
]

const wlStore = createStore(
rootReducer,
initialState
compose(applyMiddleware(...middlewares))
)

上面的内容对我来说效果很好,我可以访问商店,但我最近遇到了另一种语法:-

const wlStore=applyMiddleware(thunk,logger)(createStore)(rootReducer)

他们似乎都在做同样的工作。

有什么理由让我应该选择其中一种而不是另一种吗?优点/缺点?

最佳答案

提高可读性和便利性是使用 Compose 的主要优点。

Compose 用于当您想要将多个存储增强器传递到存储时。存储增强器是高阶函数,可为存储添加一些额外的功能。默认情况下,Redux 提供的唯一存储增强器是 applyMiddleware,但还有许多其他可用的增强器。

存储增强器是高阶函数

什么是高阶函数?转述自Haskell docs :

Higher order functions can take functions as parameters and return functions as returnvalues. A function that does either of those is called a higher orderfunction

来自 Redux 文档:

All compose does is let you write deeply nested function transformations without the rightward drift of the code. Don’t give it too much credit!

因此,当我们链接高阶函数(存储增强器)而不必编写时

func1(func2(func3(func4))))

我们可以直接写

compose(func1, func2, func3, func4)

这两行代码做同样的事情。只是语法不同。

Redux 示例

来自Redux docs如果我们不使用compose,我们就会

finalCreateStore =
applyMiddleware(middleware)(
require('redux-devtools').devTools()(
require('redux-devtools').persistState(
window.location.href.match(/[?&]debug_session=([^&]+)\b/)
)()
)
)(createStore);

如果我们使用compose

finalCreateStore = compose(
applyMiddleware(...middleware),
require('redux-devtools').devTools(),
require('redux-devtools').persistState(
window.location.href.match(/[?&]debug_session=([^&]+)\b/)
)
)(createStore);

了解有关 Redux 撰写功能的更多信息 click here

关于redux - 理解 redux 中的 compose 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41357897/

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