reducers.reduce(
(p, r) => r(p, current),
previous,
);
Reducer是一个函数数组r(p, current)
将返回一个对象。我试图从这里https://github.com/dvajs/dva/blob/master/packages/dva-core/src/handleActions.js了解源代码,但有点混淆这个陈述。什么减少到?
我试图使用reduce
函数,它似乎只是取最后一个值(如果我不像这种情况那样转换值)?
var array1 = [0, 1, 2, 3];
const result = array1.reduce((accumulator, currentValue) => currentValue);
console.log(result);
答案 0 :(得分:1)
当您查看整个功能而不是您引用的部分时,它会更容易理解:
function reduceReducers(...reducers) {
return (previous, current) =>
reducers.reduce(
(p, r) => r(p, current),
previous,
);
}
......以及调用该函数时会发生什么:
const reducer = reduceReducers(...reducers);
reduceReducers(...reducers)
返回函数,当使用reducer(state, action)
调用时,将状态作为初始值/数组并传递用作累加器p
。 action
传递为current
,因此调用reducer r
可能会根据操作创建新状态。
让我们再看看,这次注释:
// `reduceReducer` takes an array of reducers
function reduceReducers(...reducers) {
// It returns a new function that accepts 2 arguments:
// `previous` and `current`
// This function is assigned to the variable `reducer`
return (previous, current) =>
// `reducers` can still be called here because of
// the closure that formed - the returned function
// maintains its outer lexical environment
reducers.reduce(
// On each iteration the accumulator is passed in.
// In the initial iteration this is the value of `state`
// On each iteration the value of the next reducer called with
// the new state and the action is returned
(p, r) => r(p, current),
// `previous` is passed in as the initial value
// When `reducer` is called `reducer(state, action)`
// this means that `state` is `previous`
previous,
);
}
希望这更清楚一点。