redux之compose的理解


react項目添加redux的時候,用到了redux中的compose函數,使用compose來增強store,下面是一個應用:

import {createStore,applyMiddleware,compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [];

let storeEnhancers = compose(
    applyMiddleware(...middlewares,sagaMiddleware),
    (window && window .devToolsExtension) ? window .devToolsExtension() : (f) => f,
);

const store = createStore(rootReducer, initialState={} ,storeEnhancers);

上面這段代碼可以讓store與 applyMiddleware和 devToolsExtension一起使用。

 

reduce方法

 在理解compose函數之前先來認識下什么是reduce方法?
官方文檔上是這么定義reduce方法的:

reduce()方法對累加器和數組中的每個元素(從左到右)應用一個函數,將其簡化為單個值。 

看下函數簽名:

arr.reduce(callback[, initialValue])

callback
執行數組中每個值的函數,包含四個參數:

accumulator(累加器)
累加器累加回調的返回值; 它是上一次調用回調時返回的累積值,或initialValue。
currentValue(當前值)
數組中正在處理的元素。
currentIndex可選(當前索引)
數組中正在處理的當前元素的索引。 如果提供了initialValue,則索引號為0,否則為索引為1。
array可選(數組)
調用reduce()的數組
initialValue可選(初始值)
用作第一個調用 callback的第一個參數的值。 如果沒有提供初始值,則將使用數組中的第一個元素。 在沒有初 始值的空數組上調用 reduce將報錯。
下面看一個簡單的例子:
數組求和

var sum = [0, 1, 2, 3].reduce(function (a, b) {
  return a + b;
}, 0);
// sum 值為 6

這個例子比較簡單,下面再看個稍微復雜點的例子,計算數組中每個元素出現的次數:

var series = ['a1', 'a3', 'a1', 'a5',  'a7', 'a1', 'a3', 'a4', 'a2', 'a1'];

var result= series.reduce(function (accumulator, current) {
    if (current in accumulator) {
        accumulator[current]++;
    }
    else {
        accumulator[current] = 1;
    }
    return accumulator;
}, {});

console.log(JSON.stringify(result));
// {"a1":4,"a3":2,"a5":1,"a7":1,"a4":1,"a2":1}

這個例子很巧妙的利用了數組的reduce方法,在很多算法面試題中也經常用到。這里需要注意的是需要指定initialValue參數。

通過reduce函數還可以實現數組去重:

var a = [1, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7];
Array.prototype.duplicate = function() {
    return this.reduce(function(cal, cur) {
        if(cal.indexOf(cur) === -1) {
            cal.push(cur);
        }
        return cal;
    }, [])
}

var newArr = a.duplicate();

compose函數 

理解完了數組的reduce方法之后,就很容易理解compose函數了,因為實際上compose就是借助於reduce來實現的。看下官方源碼

export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

compose的返回值還是一個函數,調用這個函數所傳遞的參數將會作為compose最后一個參數的參數,從而像’洋蔥圈’似的,由內向外,逐步調用。

看下面的例子:

import { compose } 'redux'// function f
const f = (arg) => `函數f(${arg})` 

// function g
const g = (arg) => `函數g(${arg})`

// function h 最后一個函數可以接受多個參數
const h = (...arg) => `函數h(${arg.join('_')})`

console.log(compose(f,g,h)('a', 'b', 'c')) //函數f(函數g(函數h(a_b_c)))

所以最后返回的就是這樣的一個函數compose(fn1, fn2, fn3) (...args) = > fn1(fn2(fn3(...args)))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM