redux-form-reducer-to-redux

Posted by Damon on 2016-05-28

Array Reduce 方法

对于前端的同学们来说,Array自带的几个遍历方法应该都不太陌生。

map ,pop,push,reduce,reduceRight,reverse,shift,slice,some,sort,splice,toString,unshift,valueof,values

我们重点来看,reduce方法:
reduce的英文意思是 减少,缩小,归纳。我觉得归纳应该是比较的符合这里的数组操作方法的。
其作用是,对数组中的所有元素调用指定的回调函数,该会掉的返回值为累积结果,并且此返回值再下一次调用该回掉函数时作为参数提供。

1
array.reduce(cb[,initValue]);
参数 定义
array 必需,数组对象
cb 必需,接受最多四个参数function callbackfn(previousValue, currentValue, currentIndex, array)的函数,对于数组中的每个元素,reduce都会调用回掉函数一次
initValue 可选,作为初始值来启动积累,第一次调用cb时此值将会作为参数而非数组值提供

例子:

1
2
3
 initState = ''
const actions = ['Learn about actions, ','Learn about reducers, ', 'Learn about store']
const newState = actions.reduce((prevState, action)=> { return prevState + action }, initState)

Redux 中的reducer

在上面的例子中,我们能看到一些reducer的影子。
应用程序的状态类似于上面的函数中的initState和newState 给定initState之后随着action的值的不断传入给计算函数得到新的newState