【问题标题】:Redux/toolkit reset all states on logout except oneRedux/toolkit 在注销时重置所有状态,除了一个
【发布时间】:2021-04-02 21:33:53
【问题描述】:

我想重置我所有的 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。有没有更好的方法来实现上述功能?

【问题讨论】:

    标签: javascript reactjs typescript redux redux-toolkit


    【解决方案1】:

    一般来说,您的选择是:

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

    【讨论】:

    • 感谢您的反馈。我使用了第二种方法,它工作正常:)
    猜你喜欢
    • 2019-06-09
    • 2020-12-14
    • 1970-01-01
    • 2021-08-02
    • 2020-04-12
    • 2021-02-06
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多