감속기에 중복 코드가 있습니다. 속성의 이름 만 변경됩니다. 중복을 제거하려면 어떻게 리팩터링 할 수 있습니까?
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 }]
}
}
}
시험
case ADD_ITEM: {
let key = 'profit'
if(state.toggleCost){
key = 'costs'
}
return {
...state,
[key]: [...state[key], { name: action.propertyName, value: action.value, id: state[key].length + 1 }]
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다