react中的compose()
首先来看reduce方法()
这是一个数组的方法。
arr.reduce(callback[, initialValue])
callback
执行数组中每个值的函数,包含四个参数:
accumulator
(累加器)currentValue
(当前值)currentIndex
可选(当前索引)array
可选(数组)initialValue
可选(初始值)
废话不多说 直接看代码
var sum = [0, 1, 2, 3].reduce(function (a, b) {
return a + b;
}, 0);
//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}
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();
// [1,2,3,4,5,6,7]
来理解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)))
说白了就是剥洋葱,吃卷心菜