Redux API之compose

本文详细介绍了函数式编程中compose函数的应用,特别是在Redux框架中如何使用该函数来组合多个store增强器,通过实例展示了compose在实际开发中的用法。

compose(...functions)

从右到左来组合多个函数。

这是函数式编程中的方法,为了方便,被放到了 Redux 里。 当需要把多个 store 增强器 依次执行的时候,需要用到它。

参数
  1. (arguments): 需要合成的多个函数。每个函数都接收一个函数作为参数,然后返回一个函数。
返回值

(Function): 从右到左把接收到的函数合成后的最终函数。

示例

下面示例演示了如何使用 compose 增强 store,这个 store 与 applyMiddleware 和 redux-devtools 一起使用。

 1 import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
 2 import thunk from 'redux-thunk';
 3 import * as reducers from '../reducers/index';
 4 
 5 let reducer = combineReducers(reducers);
 6 let middleware = [thunk];
 7 
 8 let finalCreateStore;
 9 
10 // 生产环境中,我们希望只使用 middleware。
11 // 而在开发环境中,我们还希望使用一些 redux-devtools 提供的一些 store 增强器。
12 // UglifyJS 会在构建过程中把一些不会执行的死代码去除掉。
13 
14 if (process.env.NODE_ENV === 'production') {
15   finalCreateStore = applyMiddleware(...middleware)(createStore);
16 } else {
17   finalCreateStore = compose(
18     applyMiddleware(...middleware),
19     require('redux-devtools').devTools(),
20     require('redux-devtools').persistState(
21       window.location.href.match(/[?&]debug_session=([^&]+)\b/)
22     ),
23     createStore
24   );
25 
26   // 不使用 compose 来写是这样子:
27   //
28   // finalCreateStore =
29   //   applyMiddleware(middleware)(
30   //     devTools()(
31   //       persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))(
32   //         createStore
33   //       )
34   //     )
35   //   );
36 }
37 
38 let store = finalCreateStore(reducer);
View Code
小贴士
  • compose 做的只是让你不使用深度右括号的情况下来写深度嵌套的函数。不要觉得它很复杂。

转载于:https://www.cnblogs.com/ZSG-DoBestMe/p/5280250.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值