redux - 理解 redux 中的 compose 函数

标签 redux react-redux

我试图在 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 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

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

相关文章:

javascript - redux-saga - 如何处理多次调用回调的 API 方法

javascript - 使用 redux react 原生 index.js

javascript - 如何只更新嵌套的 Redux 状态数组中的一个值?

reactjs - react reducer 给出错误

javascript - 使用 React + Redux 获取所有选中的复选框及其相关数据

reactjs - Connect(EquipmentMetadata) 中的 mapStateToProps() 必须返回一个普通对象。相反收到了未定义的

javascript - 异步 redux 函数如何工作?

reactjs - 从 react js 中的 Prop 更新 ui。在 react 中状态切换的 Prop

javascript - 如何翻译 react-router 路由路径

reactjs - 需要react-redux v6 v3.*.* 版本的react-redux-firebase