多个状态,同一动作创建者

时间:2018-09-06 09:09:23

标签: javascript reactjs redux

我有两个计数器,COUNTER_1COUNTER_2。因此,我创建了多个reducer来处理它们。

export default (state = 0, action) => {
switch (action.type) {
 case "INCREMENT_1":
   return state + 1;
 case "DECREMENT_1":
   return state - 1;
 default:
   return state;
 }
};

这是给COUNTER_1的,也类似我创建的COUNTER_2

export default (state = 0, action) => {
 switch (action.type) {
  case "INCREMENT_2":
   return state + 1;
  case "DECREMENT_2":
   return state - 1;
  default:
   return state;
 }
};

现在我为他们创建了一个动作创建者,就像

export function increment(counterNumber) {
 let stateSelector = counterNumber === 1 ? "INCREMENT_1": "INCREMENT_2"
 return {
  type: stateSelector 
 };
}

与上面的示例中的多个reducer实例具有相同的action creator是否可以。我可能拥有COUNTER_1的其他功能,而这些功能可能不在行中的COUNTER_2那里。但是,两者的基本特征都是INCREMENTDECREMENT

这样一来,我以后就可以将功能分别添加到两个计数器中,同时保持基本功能不变。也许只为INCREMENT_BY_TWO添加COUNTER_1

2 个答案:

答案 0 :(得分:1)

您可以将相同的减速器用于不同的计数器。

function createCounterWithNamedType(counterName = '') {
    return function counter(state = 0, action) {
        switch (action.type) {
            case `INCREMENT_${counterName}`:
                return state + 1;
            case `DECREMENT_${counterName}`:
                return state - 1;
            default:
                return state;
        }
    }
}

const rootReducer = combineReducers({
    counterA : createCounterWithNamedType('A'),
    counterB : createCounterWithNamedType('B'),
    counterC : createCounterWithNamedType('C'),
});

store.dispatch({type : 'INCREMENT_B'});
console.log(store.getState());
// {counterA : 0, counterB : 1, counterC : 0const rootReducer = combineReducers({
    counterA : createCounterWithNamedType('A'),
    counterB : createCounterWithNamedType('B'),
    counterC : createCounterWithNamedType('C'),
});

store.dispatch({type : 'INCREMENT_B'});
console.log(store.getState());
// {counterA : 0, counterB : 1, counterC : 0}}

答案 1 :(得分:0)

实际上,您所在的州应同时包含两个计数器:

export default (state, action) => {
   switch (action.type) {
       case 'INCREMENT':
            return {
                ...state,
                [action.counter]: {
                     ...state[action.counter],
                     value: state[action.counter].value + 1
                }
            };

        case 'DECREMENT':
             return {
                ...state,
                [action.counter]: {
                     ...state[action.counter],
                     value: state[action.counter].value - 1
                }
            };
        default:
             return state;
     }
};

export function increment(counterNumber) {
   return {
       type: 'INCREMENT',
       counter: counterNumber
   };
}

export function decrement(counterNumber) {
   return {
       type: 'DECREMENT',
       counter: counterNumber
   };
}

以后您可以访问计数器值或任何其他计数器数据,例如:

 this.state[counterNumber].value

当然,默认状态为:

{
    1: {
        value: 0,
        someOtherProperty: false
    },
    2: {
        value: 0,
        someOtherProperty: true
    },
}