本文介绍了理解 redux 中的 compose 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to create a store in redux for which I am currently using following syntax:-

const middlewares = [
  thunk,
  logger
]

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

以上对我来说工作正常,我可以访问商店,但我最近遇到了另一种语法:-

The above works fine for me and I can access the store, but I lately I bumped into another syntax:-

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

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

Both of them seem to be doing the same job.

有什么理由让我更喜欢一个吗?利弊?

Is there any reason because of which I should prefer one over another? Pros/Cons?

推荐答案

提高可读性和便利性是使用 compose 的主要优势.

Compose 用于将多个商店增强器传递给商店.商店增强器是为商店添加一些额外功能的高阶函数.Redux 默认提供的唯一存储增强器是 applyMiddleware,但还有许多其他可用的.

Compose is used when you want to pass multiple store enhancers to the store. Store enhancers are higher order functions that add some extra functionality to the store. The only store enhancer which is supplied with Redux by default is applyMiddleware however many other are available.

商店增强器是高阶函数

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

What are higher order functions? Paraphrased from the Haskell docs:

高阶函数可以将函数作为参数,返回函数作为返回值.执行上述任一操作的函数称为高阶函数功能

来自 Redux 文档:

From the Redux docs:

compose 所做的就是让您编写深度嵌套的函数转换,而无需代码向右漂移.不要给它太多的信任!

所以当我们链接我们的高阶函数(存储增强器)而不必编写

So when we chain our higher order functions (store enhancers) instead of having to write

func1(func2(func3(func4))))

我们可以直接写

compose(func1, func2, func3, func4)

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

These two lines of code do the same thing. It is only the syntax which differs.

Redux 示例

如果我们不这样做,则来自 Redux 文档t 使用 compose 我们会有

From the Redux docs if we don't use compose we would have

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 撰写功能的更多信息单击此处

To read more about Redux's compose function click here

这篇关于理解 redux 中的 compose 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 10:25