2016-09-07 190 views
1

我的減速器如下:添加功能,減速機

const removeFilter = (state, name) => { 
    return state.filter(f => f.name !== name); 
}; 

export default function addRemoveFilterReducer(state = [], action) { 
    switch (action.type) { 

     case ADD_FILTER: 
      if(!state.some(i => i.name === action.searchFilter.name)) 
       return [...state, {name: action.searchFilter.name, values: [action.searchFilter.values]}]; 
      else 
       return [...state.filter(f => f.name !== action.searchFilter.name), {name: action.searchFilter.name, values: [action.searchFilter.values]}]; 

     case REMOVE_FILTER: 
      return [...state.filter(f => f.name !== action.searchFilter.name)]; 
     break; 

     default: 
      return state; 
    } 
} 

在的add_filter情況下其他國家和REMOVE_FILTER情況下,我有相同的代碼:...state.filter(f => f.name !== action.searchFilter.name)

我創建了一個函數使用該代碼刪除過濾器。我現在如何在我的情況下使用這個功能?

我試着用return [removeFilter(state, action.searchFilter.name, {name: action.searchFilter.name, values: [action.searchFilter.values]}];處於ADD_FILTER狀態的else狀態,但它不起作用。

有什麼建議嗎?

UPDATE

函數調用:

return [removeFilter(state, action.searchFilter.name, ......];

+0

您忘記了函數中的方括號和擴展運算符。 –

+0

還有更多,你不需要* REMOVE_FILTER *中的最後一個* break *指令,因爲你總是從函數返回。甚至* ADD_FILTER *中的* else *都可以被刪除。至於如何工作的開關,如果有東西跳*如果*,比移動到下一個* case *指令。 –

+0

我改變了它,問題依然存在。如果reducer沒有函數,我在控制檯日誌中獲得'[object]'但是如果我使用函數有或沒有變化,我得到'[Array [0],Object]' – Boky

回答

1

我建議改變這樣的代碼:

export default function addRemoveFilterReducer(state = [], action) { 
    switch (action.type) { 

     case ADD_FILTER: 
      let nState = state; 
      if(state.some(i => i.name === action.searchFilter.name)) { 
       nState = state.filter(f => f.name !== action.searchFilter.name); 
      } 

      return [...nState, {name: action.searchFilter.name, values: [action.searchFilter.values]}]; 

     case REMOVE_FILTER: 
      return state.filter(f => f.name !== action.searchFilter.name); 

     default: 
      return state; 
    } 
} 

現在你已經分裂了從添加刪除和代碼比以前清晰得多。所以,現在對你的函數

const removeFilter = (state, name) => { 
    return state.filter(f => f.name !== name); 
}; 


export default function addRemoveFilterReducer(state = [], action) { 
    switch (action.type) { 

     case ADD_FILTER: 
      let nState = state 
      if(state.some(i => i.name === action.searchFilter.name)) { 
       nState = removeFilter(state, action.searchFilter.name); 
      } 

      return [...nState, {name: action.searchFilter.name, values: [action.searchFilter.values]}]; 

     case REMOVE_FILTER: 
      return removeFilter(state, action.searchFilter.name); 

     default: 
      return state; 
    } 
} 

您已經從功能的陣列,所以你不需要把它變成另一個數組並使用傳播操作。

如果你需要克隆狀態對象,比在函數內部做它,因爲它是正確的地方。

希望這會有所幫助。

+0

在這種情況下,如果「false」,nState將始終爲空數組。但我有多個過濾器。大多數時候會有更多的過濾器。 – Boky