理解 redux 中的 compose 函数

Understanding compose functions in redux

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

const middlewares = [
  thunk,
  logger
]

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

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

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

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

有什么理由让我更喜欢一个而不是另一个吗? Pros/Cons?

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

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

商店增强器是高阶函数

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

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

来自 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