compose(...functions)
從右到左來組合多個函數。
這是函數式編程中的方法,為了方便,被放到了 Redux 里。 當需要把多個 store 增強器 依次執行的時候,需要用到它。
參數
- (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);
小貼士
compose
做的只是讓你不使用深度右括號的情況下來寫深度嵌套的函數。不要覺得它很復雜。