Javascript 在react中删除减速器中的重复代码

Javascript 在react中删除减速器中的重复代码,javascript,reactjs,Javascript,Reactjs,我在减缩器中有重复的代码。其中只有属性的名称更改。如何重构以删除重复项 const reducer = (state, action) => { switch (action.type) { case ADD_ITEM: { if (state.toggleCost) { let last = state.costs.length return { ...state,

我在减缩器中有重复的代码。其中只有属性的名称更改。如何重构以删除重复项

const reducer = (state, action) => {
switch (action.type) {
    case ADD_ITEM: {
        if (state.toggleCost) {
            let last = state.costs.length
            return {
                ...state,
                costs: [...state.costs, { name: action.propertyName, value: action.value, id: last + 1 }
                ],
            }
        } else {
            let last2 = state.profit.length
            return {
                ...state,
                profit: [...state.profit, { name: action.propertyName, value: action.value, id: last2 + 1 }]
            }

        }
    }
试一试

案例添加项目:{
让键=‘利润’
if(state.toggleCost){
键=‘成本’
}
返回{
……国家,
[key]:[…state[key],{name:action.propertyName,value:action.value,id:state[key].length+1}]
}
}

由于我不确定
属性名称
实际包含的内容,使用三元表达式
[]
属性访问器
可以帮助我们进行如下重构:-

const reducer = (state, action) => {
switch (action.type) {
    case ADD_ITEM: {  
    let fieldToUpdate = state.toggleCost ? 'costs' : 'profit';
    return {...state,[fieldToUpdate]:[...state[fieldToUpdate],{name: action.propertyName, value: action.value, id: state[fieldToUpdate].length + 1}]}
      
    }