简体   繁体   中英

How combineReducers know which slice to pass REDUX

I'm little bit confused about how combineReducers will pass reducers their needed slice of state.

For example i my state looks like this:

{
    products: [somedata],
    comments: [somedata]
}

and I have 2 reducers for handling changes in them (1-productReducer, 2-commentReducer)

in my root reducer i have

const rootReducer = combineReducer(
    products: productReducer,
    comments: commentReducer
)

Lets imagine products and comment are two different things and have no connection together and i want to just pass state.products to productReducer and state.comment to commentReducer. That so obvious I don't need comments in productReducer . But how does this combineReducer handle this?!

If I want to do this I would write:

function rootReducer(state, action) {
    products: productReducer(state.products),
    comments: commentReducer(state.comments)
}

But I wonder combineReducer even cares about slicing data and passing them to appropriate reducer.

I see people are linking to the source code or the documentation but maybe a simple explanation will help you understand.

When you call combine reducers, each reducer will return it's initial slice of the pie, combine reducers simply takes this slice of the pie and stores it in a map using the same name as to which the reducer is registered, when an action is dispatched, it simply takes the slice it was stored for each reducer and passes it again in order to produce the next state.

you call:

combineReducers({
  foo: fooReducer,
  bar: barReducer,
})

internally the state gets stored:

combinedState = {
  foo: fooState, // the state returned by the initial call to the foo reducer
  bar: barState, // the state returned by the initial call to the bar reducer 
}

when an action is dispatched, something like this occurs:

combinedState = {
  foo: fooReducer(fooState, action), // generate the next state
  bar: barReducer(barState, action), // generate the next state
}

combineReducer(products: productReducer, comments: commentsReducer) , will create single state object and differentiate between them using keys (products, comments) passed to it.

rootReducer = combineReducer(products: productReducer, comments: 
commentsReducer);
   // This would produce the following state object
  {
  products: {
   // ... products, and other state managed by the productReducer ...
  },
  comments: {
   // ... comments, and other state managed by the commentsReducer
  }
}

Here this concept is defined.

Update:

combineReducer calls all reducers it's wrapping with action dispatched, giving reducers a chance to respond. Please follow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM