如何在每个模块结束后将Redux Store重置为初始状态?
如何在模块结束后重置Redux Store到初始状态
核心解决方案
要实现周期结束后重置计数器并按需保留历史记录,可通过以下步骤完成:
- 新增重置Action
在Action.ts中添加触发状态重置的Action:
export const readCounter = createAction( '[Cycle Counter] read cycle counter', props<{counter: Counter}> () ); // 新增重置计数器的Action export const resetCounter = createAction('[Cycle Counter] reset cycle counter');
- 修正Reducer并添加重置逻辑
原Reducer存在每次调用都重复创建createReducer的问题,先将其移至外部,再添加重置处理逻辑:
export interface Counter { count: number } export const initialState: Counter = { count:0 }; // 将createReducer移至外部,避免重复初始化 const counterReducer = createReducer( initialState, on(readCounter, (state, { counter }) => ({ count: counter.count })), // 处理重置请求,直接返回初始状态 on(resetCounter, () => initialState) ); export const indexReducer = (state: any, action: any): Counter => { return counterReducer(state, action); };
- 在周期结束时触发重置
当第一个周期完成后,在业务逻辑中调用dispatch触发重置:
// 示例:周期结束的处理函数 const finishCycle = () => { dispatch(resetCounter()); // 执行新周期启动逻辑 };
保留历史记录的优化方案
如果需要保留之前周期的计数记录,无需重置整个store,可扩展状态结构:
// 扩展状态结构,新增历史记录字段 export interface CounterState { currentCount: number; cycleHistory: number[]; } export const initialState: CounterState = { currentCount: 0, cycleHistory: [] }; const counterReducer = createReducer( initialState, on(readCounter, (state, { counter }) => ({ ...state, currentCount: counter.count })), on(resetCounter, (state) => ({ ...state, currentCount: 0, // 将当前周期的最终计数存入历史列表 cycleHistory: [...state.cycleHistory, state.currentCount] })) );
该方案既重置了当前计数器以开启新周期,又不会丢失之前的周期数据,解决了Redux DevTools重置导致记录丢失的问题。
内容的提问来源于stack exchange,提问作者Curtis Lanz
相关产品推荐
相关产品推荐

