Redux reducers initializing same state key

前端 未结 2 1400
[愿得一人]
[愿得一人] 2021-02-07 07:23

I\'m messing around with the \'simplest-redux-example\' on github and I\'ve added a second reducer that decrements state.count. If I have the increment and decrement reducers i

2条回答
  •  难免孤独
    2021-02-07 08:04

    The reducers passed to combineReducers get different pieces of the state object.

    The resulting reducer calls every child reducer, and gather their results into a single state object. The shape of the state object matches the keys of the passed reducers.

    (Emphasis mine)

    So, the internal state object would look like

    {
      counter: result of passing `state.counter` into counter reducer
      decrementer: result of passing `state.decrementer` into decrementer reducer
    }
    

    This is analogous to having separate stores in a flux application, where each store both operates its own "piece" of the global app state.

    Since you actually want these two reducers to work on the same portion of the state object, you actually want something more like reduce-reducers, though it's very easy to implement yourself—just pass the state into each reducer in turn, reducing the initial state with the new state from each reducer.

    In fact, it's so simple, the implementation is just a few lines:

    export default function reduceReducers(...reducers) {
      return (previous, current) =>
        reducers.reduce(
          (p, r) => r(p, current),
          previous
        );
    }
    

    and your rootReducer would be

    const rootReducer = reduceReducers(counter, decrementer);
    

提交回复
热议问题