【问题标题】:Is there a way to reset store to initialState after end of each module?有没有办法在每个模块结束后将存储重置为 initialState?
【发布时间】:2022-11-28 06:17:34
【问题描述】:

我还没有实现它,但我有一个计数器状态,它计算 3 轮循环。在第一个循环之后,我希望计数器在另一个循环中重置为 0。

动作.ts

export const readCounter = createAction(
    '[Cycle Counter] read cycle counter',
    props<{counter: Counter}> ()
);

这非常适用于第一个周期,即 3 轮

export interface Counter {
count: number
}

export const initialState: Counter = {
    count:0
};

export const indexReducer = ( state: any, action: any): Counter => {
    const reducer = createReducer(
        initialState,
        on(readCounter, (state, { counter }): any => (
            {
                count: counter.count
            }
        ))
        
        );
    return reducer(state, action);
};

所以当我开始第二个循环时,第二个循环由 10 个回合组成,不是从 1 开始,而是从 4 开始(从 3 开始)。

我有相同的逻辑,但在不同的模块中。我的组件使用同一个商店。我尝试使用不同的计数器,但出现错误。所以在每个循环之后,重置 redux devTool,它会刷新并从 1 开始,但我会在第一个循环中丢失记录。

【问题讨论】:

    标签: angular ngrx


    【解决方案1】:

    状态是全局的,因此您需要为每个模块使用不同的状态属性,并执行不同的操作。

    export const readCounterModule1 = createAction(
        '[Cycle Counter] read cycle counter module 1',
        props<{count: number}> ()
    );
    
    export const readCounterModule2 = createAction(
        '[Cycle Counter] read cycle counter module 2',
        props<{count: number}> ()
    );
    
    export const initialState: Counter = {
        module1count: 0,
        module2count: 0
    };
    
    export const indexReducer = ( state: any, action: any): Counter => {
        const reducer = createReducer(
            initialState,
            on(readCounterModule1, (state, { count }): any => (
              {
                module1count: count
              }
            )),
            on(readCounterModule2, (state, { count }): any => (
              {
                module2count: count
              }
            ))
         );
        return reducer(state, action);
    };
    
    

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2012-02-22
      • 2018-07-06
      • 2021-03-22
      • 2011-03-08
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多