我正在将Angular 2与ngrx/store一起使用。我想在用户调度USER_LOGOUT时重置整个商店状态。

我读了Dan Abramov对How to reset the state of a Redux store?的回答,但我不知道如何正确编写rootReducer以及在使用ngrx / store时将其放在何处。

还是有其他方法可以在ngrx / store中处理此问题?

bootstrap(App, [
    provideStore(
      compose(
        storeFreeze,
        storeLogger(),
        combineReducers
      )({
        router: routerReducer,
        foo: fooReducer,
        bar: barReducer
      })
    )
  ]);

最佳答案

此答案特定于ngrx版本2。该问题的another, more recent answer解释了如何使用ngrx版本4进行相同的操作。
compose构建ngrx 根减少器

传递给compose的参数是返回 reducer 的函数-由 reducer 组成,它们本身作为参数传递。您可以像下面这样组成商店的重置:

import { compose } from "@ngrx/core/compose";

...

bootstrap(App, [
  provideStore(
    compose(
      storeFreeze,
      storeLogger(),
      (reducer: Function) => {
        return function(state, action) {
          if (action.type === 'USER_LOGOUT') {
            state = undefined;
          }
          return reducer(state, action);
        };
      },
      combineReducers
    )({
      router: routerReducer,
      foo: fooReducer,
      bar: barReducer
    })
  )
]);

请注意,这将重置商店的所有状态-包括router。如果这不是您想要的,则可以调整示例。

随着NgModule的引入, bootstrap 已更改,但是您仍将组成的reducer传递给provideStore:
import { compose } from "@ngrx/core/compose";
import { StoreModule } from "@ngrx/store";

@NgModule({
    ...
    imports: [
        ...
        StoreModule.provideStore(compose(...))
    ],
    ...

07-24 18:05
查看更多