2017-06-01 41 views
0

我寫了一個redux reducer,幫助我從其他reducer組錯誤消息。Reducer檢查action.type與indexOf

我想知道這是否會有任何副作用,因爲我沒有看到任何人這樣做。我也想知道是否有更好的方法來做到這一點,我想不到。

這是我寫的:

const errors = (state = {}, action = {}) => { 

    let new_state = Object.assign({}, state); 

    // if action type contains ERROR and action error is present 
    if (action.type.indexOf("ERROR") != "-1" && action.error) { 
     let error_id = Utils.hashCode(action.error); 

     // if error already in the array 
     if (new_state[error_id]) { 
      new_state[error_id].count++; 
     } 

     // otherwise add the message to the list 
     else { 
      new_state[error_id] = {message: action.error, count: 1}; 
     } 
    } 

    // regular switch stmt 
    switch (action.type) { 
     case ERRORS_RESET: new_state = {}; break; 
    } 

    return new_state; 
} 

我的店現在看起來是這樣的:

{ 
    reducer1: { 
     something: [], 
     error: "Some error message", 
    }, 
    reducer2: { 
     something: [], 
     error: false, 
    }, 
    reducer3: { 
     some_other_obj: {}, 
     error: "Another error message", 
    }, 
    errors: [ 
     {message: "Some error message, count: 1} 
     {message: "Another error message", count: 2} 
    ] 
} 

回答

1

監聽"SOMETHING_ERROR"行動的整體概念是好的,但有一對夫婦的問題與你的實現。

首先,您的if聲明具有現有狀態的直接變體。根據Redux文檔的Structuring Reducers - Immutable Update Patterns部分,您需要確保您每複製嵌套級別。現在你正在複製狀態的第一層,而不是嵌套對象。

第二,你是總是複製狀態,即使沒有什麼實際改變。這通常會導致您的用戶界面中不必要的重新渲染。

+1

謝謝!對於第一點,我仍然需要掌握它,主要是因爲我編寫的減速器只需要關心平面物體。對於第二點,我從來沒有想過,這實際上是很有道理的。 – pnknrg