"Unexpected key "foo“在redux-toolkit配置存储和自定义存储增强器中发现reducer接收到的先前状态”
"Unexpected key "foo" found in previous state received by the reducer" with redux-toolkit configure store and a custom store enhancer
我一直在尝试创建一个商店增强器,为我的根状态添加一些新值。但是,在仔细研究了自定义增强器的所有工作原理之后,我遇到了意外的关键错误。我可以在 devtools 中看到状态的新部分并且应用程序似乎工作正常,但是我得到
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.
我根本不明白。我尝试四处搜索,但我找到的 none 个帖子是关于自定义商店增强器的。
这是重现上述错误的最少代码。我正在这样创建我的商店:
export const store = configureStore({
reducer: mainReducer,
enhancers: [testEnhancer],
});
其中 mainReducer 只是 combineReducers({ "my slices" }),所有切片都是使用 RTK 的 createSlice 创建的。
testEnhancer 如下所示:
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: '' });
};
};
这实际上是 combineReducers
特有的行为。它期望任何顶级状态键和关联的切片缩减器之间的永久 1:1 映射。
您需要以某种方式设置自定义减速器来处理此问题,或者不根本不使用combineReducers
。 (有许多类似的版本执行相同的整体行为,但也减去了警告。)
我一直在尝试创建一个商店增强器,为我的根状态添加一些新值。但是,在仔细研究了自定义增强器的所有工作原理之后,我遇到了意外的关键错误。我可以在 devtools 中看到状态的新部分并且应用程序似乎工作正常,但是我得到
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.
我根本不明白。我尝试四处搜索,但我找到的 none 个帖子是关于自定义商店增强器的。
这是重现上述错误的最少代码。我正在这样创建我的商店:
export const store = configureStore({
reducer: mainReducer,
enhancers: [testEnhancer],
});
其中 mainReducer 只是 combineReducers({ "my slices" }),所有切片都是使用 RTK 的 createSlice 创建的。
testEnhancer 如下所示:
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: '' });
};
};
这实际上是 combineReducers
特有的行为。它期望任何顶级状态键和关联的切片缩减器之间的永久 1:1 映射。
您需要以某种方式设置自定义减速器来处理此问题,或者不根本不使用combineReducers
。 (有许多类似的版本执行相同的整体行为,但也减去了警告。)