简体   繁体   中英

“Unexpected key ”foo“ found in previous state received by the reducer” with redux-toolkit configure store and a custom store enhancer

I have been trying to create a store enhancer that adds some new values to my root state. However after wrapping my head around all the workings of custom enhancer I am getting an unexpected key error. I can see the new part of state in devtools and the application seems to work fine, however I am getting

Unexpected key "foo" found in previous state received by the reducer. 
Expected to find one of the known reducer keys instead: [...]. Unexpected keys will be ignored.

Which I simply do not understand. I tried searching around, but none of the posts I found were with the case of a custom store enhancer.

Here is the minimum code that reproduces said error. I am creating my store like this:

export const store = configureStore({
    reducer: mainReducer,
    enhancers: [testEnhancer],
});

Where mainReducer is just combineReducers({ "my slices" }) and all the slices are created with createSlice from RTK.

The testEnhancer looks like this:

type StateExt = { foo: string }
export const testEnhancer: StoreEnhancer<{}, StateExt> = (next: StoreEnhancerStoreCreator): StoreEnhancerStoreCreator<{}, StateExt> => {
    
    return <S, A extends Action = AnyAction>(reducer: Reducer<S, A>, preloadedState?: PreloadedState<S>): Store<S & StateExt, A> => {
        
        const wrappedReducer: Reducer<S & StateExt, A> = (state, action) => {
            return { ...reducer(state, action), foo: 'bar' };
        };
        
        return next(wrappedReducer, { ...preloadedState, foo: '' });
    };
};

This is actually behavior that is specific to combineReducers . It expects a permanent 1:1 mapping between any top-level state keys and associated slice reducers.

You'll need to have a custom reducer set up somehow that handles this, or not use combineReducers at all. (There are many similar versions out there that do the same overall behavior but minus the warnings as well.)

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