首页 > 解决方案 > Redux/toolkit 在注销时重置所有状态,除了一个

问题描述

我想重置我所有的 redux 对象,除了一个(目前)。我正在使用的代码正在运行,但我认为它效率不高,因为每次添加新切片时,我都必须更新以下代码:

// app reducers
const combinedReducer = combineReducers({
    auth,
    general,
    books,
    authors,
    events
});

// reducers type
export type AppReducerType = ReturnType<typeof combinedReducer>;

// root reducer
const rootReducer = (rootState: AppReducerType | undefined, action: AnyAction) => {
    // terminate the state of a redux store
    if (action.type === 'Auth/terminate') {
        if (rootState) {
            rootState = {
                ...rootState,
                auth: aState,                   // reset state
                general: rootState.general,     // keep it as it is
                books: bState,                  // reset state
                authors: auState,               // reset state
                events: eState,                 // reset state
            };
        }
    }
    return combinedReducer(rootState, action);
};
export default rootReducer;

如果我使用rootState = undefined,那么它会重置所有状态,包括general我不想要的状态。有没有更好的方法来实现上述功能?

标签: javascriptreactjstypescriptreduxredux-toolkit

解决方案


一般来说,您的选择是:

  • 让每个单独的切片重置自己的状态以响应相同的操作
  • 保留初始状态的副本,并执行以下操作:
return {
  ...initialRootState,
  auth: state.auth
}

推荐阅读