我如何一起使用combineReducers和reduceReducers?

时间:2017-04-11 15:45:13

标签: reactjs redux reducers

如何将combineReducers和reduceReducers一起使用?我想使用一些reducer作为组合,但我还需要一些应该管理所有状态的reducer(不仅仅是在combineReducer中的一部分)。 我尝试使用:

const combinedReducers = combineReducers({reducerA});
export const reducers= reduceReducers(combinedReducers, reducerB);

对于相同的结构: interface State{ reducerAState: reducerA; reducerBState: reducerB; }

但是在这种情况下,reducerA只会自己覆盖所有状态,而没有先前的状态。

1 个答案:

答案 0 :(得分:2)

这种方式不可行。 combineReducers生成的Reducer将使用不是其初始化key-to-reducers映射的一部分的键删除状态部分。这就是你所经历的,也就是它如何通过设计工作。

如果确实必须坚持combineReducersreducerReducers来解决您的任务,那么您必须实施3个减速器:一个用于切片A ,一个用于切片B,另一个用于两个切片:

const sliceA = (state, action) => state + `| ${action.type} by A`;
const sliceB = (state, action) => state + `| ${action.type} by B`;
const full = (state, action) => ({ sliceA: state.sliceA + `| ${action.type} by C`, sliceB: state.sliceB + `| ${action.type} by C` });

const reducer = reduceReducers(
  combineReducers({ 
    sliceA,
    sliceB,
  }),
  full
);

const initialState = { sliceA: 'initial A', sliceB: 'initial B' };
const action = { type: 'touched' };

console.log(reducer(initialState, action));

// outputs:

Object {
  sliceA: "initial A| touched by A| touched by C",
  sliceB: "initial B| touched by B| touched by C"
}

但是自己编写它可能更容易:

const sliceA = (state, action) => state + `| ${action.type} by A`;
const sliceB = (state, action) => ({ 
  sliceA: state.sliceA + `| ${action.type} by B`, 
  sliceB: state.sliceB + `| ${action.type} by B`, 
})

const reducer = (state, action) => sliceB(
  {
    sliceA: sliceA(state.sliceA, action),
    sliceB: state.sliceB,
  }, 
  action
)
const initialState = { sliceA: 'initial A', sliceB: 'initial B' };
const action = { type: 'touched' };

console.log(reducer(initialState, action));

// outputs:
Object {
  sliceA: "initial A| touched by A| touched by B",
  sliceB: "initial B| touched by B"
}