Recently, a problem was encountered when REdux was used in the project: Multiple Reducer management states (such as ruducerA, reducerB) were used. When data was updated through action, the current reducerA data was successfully updated, but another reducerB data was initialized.

This behavior made me very confused. I searched for a long time and couldn’t find a starting point. The code is as follows:

APP.js

const rootReducer = combineReducers({
  RudecerA,
  RudecerB,
});
 
const store = createStore(
	rootReducer
);
 
 
export default function App(props) {
  return (
    <Provider store={store}>
    	<Router {. props} / >
    </Provider>
  );
}
Copy the code

reducerB.js

export function ReducerB(state = initState, action,) {
    switch (action.type) {
      case UPDATE_RECORD_DATA:
        return { ...state, recordData: action.payload };
       case DELETE_RECORD_DATA:
         return { ...state, recordData: initRecordData };
        default:
    	  returninitState; }}Copy the code

The solution

Later, the combineReducer is introduced and noted in the official document:

Any unmatched action must return the state as the first argument it received.

I suddenly found hope here, because I returned initState by default in reducerB. I tried to change initState to state, and it worked!

But why does combineReducer require state to be returned by default?

Ask back

The first thing we want to do with combineRuducer is to manage the state by slicing it, which will eventually merge all the states and return.

export function combineReducers<S> (
  reducers: ReducersMapObject<S, any>
) :Reducer<CombinedState<S>>
Copy the code

By looking at the source code, we find that combineRudecer mainly does the following things:

  • Filter invalid reducer
  • All the legitimate reducers are traversed and the new state is obtained
  • Check whether state is updated and return the new value if it is updated and vice versa.
  • Merge all states and return.

conclusion

In normal development, when the switch case is used, the default value will be assigned to initState to prevent errors in the program.

In combineReducer, whenever an action is initiated, the current Reducer will go into the case and return the expected result, but there is no matching condition in the other Reducer and the initial value is returned.

Sometimes it’s a waste of energy to write down bugs that are difficult to detect because of inertia. When using these libraries, you should understand how they work and avoid detdetments.