【问题标题】:NGRX - What is the best way to reset the entire state?NGRX - 重置整个状态的最佳方法是什么?
【发布时间】:2020-01-26 13:02:43
【问题描述】:

当我们有不同的减速器时,重置整个状态的最佳方法是什么? 我在使用选择器时遇到了这个问题,因为当我重置时它不会给我带来初始状态

元减速器

import { ActionReducer } from '@ngrx/store';
import { UserActionTypes } from '../../actions/actionTypes';

export function clearStateReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === UserActionTypes.Logout) {
      state = undefined;
    }
    return reducer(state, action);
  };
}

状态模块

import { NgModule } from '@angular/core';
import { StateService } from './state.service';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { StoreModule } from '@ngrx/store';
import { appReducer } from './reducers';
import { getInitialState } from './state';
import { metaReducers } from './reducers/metaReducers';

@NgModule({
  imports: [
    StoreModule.forRoot(appReducer, {
      initialState: getInitialState(),
      metaReducers,
      runtimeChecks: {
        strictStateImmutability: false,
        strictActionImmutability: false,
        strictStateSerializability: false,
        strictActionSerializability: false
      }
    }),
    StoreDevtoolsModule.instrument({
      maxAge: 25
    })
  ],
  providers: [StateService]
})
export class StateServiceModule {}

【问题讨论】:

  • 你目前的做法是什么?
  • 刷新页面将以初始ngrx状态启动应用程序。除此之外,您可能还想使用 meta-reducer。第三种选择是为每个 reducer 添加一个新动作和新案例,并从 resetState$ 效果中触发它们。
  • 你能在 stackblitz 中分享你的代码吗?你在使用本地存储吗?
  • 我正在使用这个 metaReducer - 导出函数 clearStateReducer(reducer: ActionReducer): ActionReducer { return (state, action) => { if (action.type === UserActionTypes.Logout ) { 状态 = 未定义; } 返回减速器(状态,动作); }; }
  • @Jose 那么有什么问题 - 它应该重置整个状态。

标签: angular redux ngrx


【解决方案1】:

你不能分配状态,而是用undefined调用reducer:

export function clearStateReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === UserActionTypes.Logout) {
      return reducer(undefined, action);
    }
    return reducer(state, action);
  };
}

【讨论】:

    【解决方案2】:

    您可以通过将状态设置回初始状态来像这样重置

    export const postReducer = createReducer(
      initialState,
      on(PostActions.ResetState, (state) => {
        return { state: initialState };
      }),
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 2015-04-28
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多