2016-05-26 6 views
1

私が理解することは、私は私が読んフラックス/ Reduxのの文脈で用語「ピュアリデューサー」を発生しているしかし、私はこのvideoで説明してしまった「ピュア機能」の概念と、この質問What is pure functions?純粋なレデューサーとは何ですか?

があるということですthis link

にしかし、私は減速にこの「純粋なコンセプトを」どのように適用するか全くわからないんだけど、純粋な減速は何ですか?

+2

還元剤は機能です。特定の種類のものですが、単なる関数です。同じこと。他の名前でバラ... – dandavis

+0

リデューサーは関数なので、もっと具体的な名前です。 –

答えて

4

ここで私の理解ですが、reduxの観点からは、2つの引数(状態、アクション)を受け入れる関数です。

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

はReduxのは、レデューサーは、現在の状態を受け入れず、状態を変化させませんことを前提としていますが、アクションの種類に応じて、新しい状態を返します。それが遵守し、状態を突然変異させないならば、それは純粋な減量剤である。

/**********************純粋減速の例****************** ***********/

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; 
} 
0

還元剤は単純に、配列の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) 

これは基本的に還元剤です。

関連する問題