什么是纯还原剂?

时间:2016-05-26 08:13:18

标签: javascript reactjs

我的理解是有一个“纯粹的功能”的概念,我在这个video和这个问题What is pure functions?中解释了

然而,我在this link

上读到的助焊剂/还原剂的背景下遇到了“纯还原剂”一词

但我不完全确定如何将这种“纯粹概念”应用于减速器,什么是纯减速器?

3 个答案:

答案 0 :(得分:5)

根据我的理解,就redux而言,reducer是一个接受两个参数(state,action)的函数。

 1. state represents the current state of the application in store
 2. action represents the action that triggered

Redux假设reducer确实接受当前状态并且不改变状态但返回新状态,具体取决于操作类型。如果它坚持并且不会改变状态那么它就是一个纯粹的减速器。

/ **********************纯减速机的例子******************* ********** /

 var initialState = {counter:0};
 function counterReducer(state = initialState, action){
     if (action.type === 'INCREMENT'){
         // returns a new state incrementing a counter
         return {counter:state.counter + 1};
     }
     else if (action.type === 'DECREMENT'){
         // return a new state decrementing a counter
        return {counter:state.counter - 1};
     }

     //  returns the state as is
     return state;
 }

只要使用相同的参数集调用上述函数,它就没有副作用,它总是返回相同的输出。

/ *********************不纯的减速机示例******************** ******* /

var initialState = {counter:0};
 function counterReducer(state = initialState, action){
     if (action.type === 'INCREMENT'){
         // modifies state by mutating or incrementing the counter in state
         state.counter++;
     }
     else if (action.type === 'DECREMENT'){
         // modifies state by mutating or decrementing the counter in state
        state.counter--;
     }

     //  returns the state
     return state;
 }

答案 1 :(得分:0)

reducer只是一个函数,它作为参数传递给数组的reduce函数。例如:

const sumReducer = (acc, x) => acc + x
const multReducer = (acc, x) => acc * x

const sumResult = [1,2,3,4,5].reduce (sumReducer, 0)
const multResult = [1,2,3,4,5].reduce (multReducer, 1)

那基本上是减速器。

答案 2 :(得分:-1)

不纯归约器的另一种形式是在给定相同参数的情况下不返回相同值的形式。因此,使用Dhananjaya Kuppu的示例:

return {counter: state.counter + Math.floor(Math.random())}