2016-08-12 84 views
0

鑑於one of react-redux's official hello world example,如何實現multiply減速器?他們實現了一個增加兩個數字的減速器,但是看到一個輸入作爲乘數的減速器也是有益的。我知道這是非常基本的,但它是我另一個項目的分解版本。向最簡單的Redux添加乘法減速器示例

這裏是我在使這項工作的嘗試:

const MULTIPLY_ACTION = 'MULTIPLY_ACTION' 
    function multiplyAction(integer) { 
    return { 
     type: MULTIPLY_ACTION, 
     integer 
    } 
    } 

export function multiplier(state = { integer: 0 }, action) { 
    switch() { 
    case MULTIPLY_ACTION: 
     console.log('multiplying', action) 
     return { 
     multiple: state.integer * action.multiplier 
     } 
    default: 
     return state 
    } 
} 

問題我遇到:

  1. 重構,使mapStateToProps()與多個減速工作。我錯過了什麼? [請參閱下面的重構]
  2. increaseAction對象文字重構爲函數(動作類型?)。在原始示例中,當我將const increaseAction = { type: 'increase' }重構爲const increaseAction =() => {type: 'increase'}時,計數器縮減器不再被調用,並且我的應用程序默默失敗(我正在使用create-react-app作爲構建版本)。

[重構]。

function mapStateToProps(state) { 
    const { increaseAction, multiplyAction } = state 

    return { 
    increaseAction, 
    multiplyAction 
    } 
} 

非常感謝!

回答

1

首先,你的動作作爲一個對象被分派給你的reducer,所以你需要使用你定義的對象形狀。例如,您將您的操作定義爲具有一個類型:MULTIPLY_ACTION,以及(通過使用屬性簡寫語法)一個名爲integer的屬性,將其設置爲integer參數的值。

因此,您的reducer需要根據類型進行切換(您現在在switch語句中有一個空的表達式,而不是說action.type),然後它需要使用action.integer

然後,你的reducer代表你的總應用程序狀態對象的一部分。現在您將該狀態的默認形狀定義爲integer屬性的值爲0的對象。您會希望動作case語句返回與默認狀態對象相同的形狀,所以它應該返回對象具有稱爲integer的單個屬性。換句話說,你的reducer應該總是返回相同的對象形狀(即使屬性不同也可能爲null,如果這對你的應用程序來說是一個有效值)。上面寫着:

return { integer: state.integer * action.integer } 

至於你的連接功能,mapStateToProps只知道你的狀態(不是你的行動),因此它只是需要返回所需狀態的一部分。它是第二個參數,mapDispatchToProps,與您的操作有關。所以,你想要的東西,如:

connect(
    state => ({ 
    multiplierInteger: state.multiplier.integer // remember that you are looking within your reducer multiplier which contains an object that has the field you want, integer 
    }), 
    dispatch => ({ 
    multiplyAction(val) { 
     dispatch(multiplyAction(val)) 
    } 
    }) 
) 

編輯:這可能是我誤會了你的「重構」,現在看到你問有關使用mapStateToProps訪問多個減速。那麼我仍然認爲我的例子可能會有所幫助,因爲你試圖通過相關行爲的名稱來訪問reducer的結果。你想要的是使用reducer本身的名稱,假設你使用combineReducers,它是Redux如何將許多reducer映射到單個狀態對象。