【问题标题】:Resetting state in ngxs在ngxs中重置状态
【发布时间】:2018-11-18 01:33:55
【问题描述】:

当我向我的状态添加一些新数据时,新数据不会出现在我的日志或 DevTool Ui 中。

是否有一种机制可以重置状态,以便数据出现。似乎某些缓存中的旧数据仍在显示。

谢谢

【问题讨论】:

  • 请提供详细信息(例如示例代码)来描述您所做的事情?

标签: ngxs


【解决方案1】:

在 v3.1 中,商店中有一个 reset 函数,可让您重置状态,请参阅文档 here

【讨论】:

    【解决方案2】:

    我更喜欢使用这个重置插件; https://github.com/ng-turkey/ngxs-reset-plugin

    这是一个 ngxs 插件,易于实现。

    【讨论】:

      【解决方案3】:

      对于状态重置,我尝试通过插件 (https://ngxs.gitbook.io/ngxs/advanced/meta-reducers) 使用“meta-reducer”概念,但我无法将每个切片的状态重新初始化为默认值。

      【讨论】:

        【解决方案4】:

        您可以简单地将操作添加到您的app.state.ts 文件中,如下所示

        重置状态的动作

        @Action(ResetAppState)
        resetState(ctx: StateContext<AppStateModel>): Observable<AppStateModel> {
           return of(ctx.getState()).pipe(
              map(currentState => {
                 ctx.patchState({/* enter initial/reset values here */});
                 return currentState;
              })
           );
        }
        

        您还必须将操作添加到app.action.ts 文件中

        export class ResetAppState {
          static readonly type = '[AppState] Reset App State';
        }
        

        现在您可以轻松地在 servicecomponent 中分派操作以重置 NGXS 状态,如下所示:

        constructor(private store: Store) {}
        
        yourMethod(): void {
            this.store.dispatch(new ResetAppState());
        }
        

        【讨论】:

          猜你喜欢
          • 2019-02-01
          • 2019-08-02
          • 2018-12-23
          • 2019-03-27
          • 2019-01-17
          • 2023-02-23
          • 1970-01-01
          • 2018-10-11
          • 1970-01-01
          相关资源
          最近更新 更多