我的减速机如下:
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情况,但它不起作用。
有什么建议吗?
更新
函数调用:
return [removeFilter(state, action.searchFilter.name, ......];
答案 0 :(得分: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;
}
}
您已经拥有该功能的数组,因此您不需要将其放入另一个阵列并使用传播操作。
如果需要克隆状态对象,请在函数内部进行克隆,因为它是正确的位置。
希望这有帮助。