简体   繁体   中英

Redux: combineReducers shape independent

Trying to split my single reducer into different reducers combineReducers is the handy function redux provides for this purpose. combineReducers though restrict the state to a specific state with a reducer for at least each first-level state key. So in some cases you either have to add more than needed reducers or change the shape of your state.

To be more concrete assume that the store of the application is like:

let store = {
    a: true,
    b: false,
    c: {...}
    d: {...}    
}

For the above store I need to define a reducer for each of the above keys and combine them, so this will be something like:

const reducerA = (state, action) => {...}
const reducerB = (state, action) => {...}
const reducerC = (state, action) => {...}
const reducerD = (state, action) => {...}

const rootReducer = combineReducers({
    a: reducerA,
    b: reducerB,
    c: reducerC,
    d: reducerD
});

I'd like to keep reducerC & reducerD for handling the respective objects on the state, but I need to have a common reducer for a & b keys on the state.

How can I add root level state key-values without defining these extra reducers reducerA & reducerB or adding a parent object with the common reducer reducerAB ? Is this possible using combineReducers or should I approach the needed behavior differently?

No, the intended use case for combineReducers is to specifically split up the logic for maintaining each slice of state, and delegate that work to separate functions. If you actually want both a and b to be managed by the exact same function instance, you either need to put them together into a slice (like state.ab.a ), or use something other than combineReducers in some way.

You may want to read through the Structuring Reducers - Beyond combineReducers section in the Redux docs for some discussion on additional ways to organize reducer logic, as well as the Redux FAQ question on sharing state between reducers .

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