2016-09-07 187 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