Redux/toolkit 在注销时重置除一个之外的所有状态
Redux/toolkit reset all states on logout except one
我想重置除一个(目前)之外的所有 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
。有没有更好的方法实现上述功能?
一般来说,您的选择是:
- 让每个切片重置自己的状态以响应相同的操作
- 保留初始状态的副本,然后执行以下操作:
return {
...initialRootState,
auth: state.auth
}
我想重置除一个(目前)之外的所有 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
。有没有更好的方法实现上述功能?
一般来说,您的选择是:
- 让每个切片重置自己的状态以响应相同的操作
- 保留初始状态的副本,然后执行以下操作:
return {
...initialRootState,
auth: state.auth
}