compose(...functions)
從右到左來組合多個函數(shù)。
這是函數(shù)式編程中的方法,為了方便,被放到了 Redux 里。當需要把多個 store 增強器 依次執(zhí)行的時候,需要用到它。
(Function): 從右到左把接收到的函數(shù)合成后的最終函數(shù)。
下面示例演示了如何使用 compose
增強 store,這個 store 與 applyMiddleware
和 redux-devtools 一起使用。
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import * as reducers from '../reducers/index';
let reducer = combineReducers(reducers);
let middleware = [thunk];
let finalCreateStore;
// 生產(chǎn)環(huán)境中,我們希望只使用 middleware。
// 而在開發(fā)環(huán)境中,我們還希望使用一些 redux-devtools 提供的一些 store 增強器。
// UglifyJS 會在構建過程中把一些不會執(zhí)行的死代碼去除掉。
if (process.env.NODE_ENV === 'production') {
finalCreateStore = applyMiddleware(...middleware)(createStore);
} else {
finalCreateStore = compose(
applyMiddleware(...middleware),
require('redux-devtools').devTools(),
require('redux-devtools').persistState(
window.location.href.match(/[?&]debug_session=([^&]+)\b/)
),
createStore
);
// 不使用 compose 來寫是這樣子:
//
// finalCreateStore =
// applyMiddleware(middleware)(
// devTools()(
// persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))(
// createStore
// )
// )
// );
}
let store = finalCreateStore(reducer);
compse
做的只是讓你不使用深度右括號的情況下來寫深度嵌套的函數(shù)。不要覺得它很復雜。
更多建議: