如何重置ngrx/store的所有状态? [英] How to reset all states of ngrx/store?

查看:223
本文介绍了如何重置ngrx/store的所有状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Angular 2 with ngrx/store. I want to reset the whole store states when user dispatch USER_LOGOUT.

我阅读了丹·阿布拉莫夫(Dan Abramov)对>如何重置,但是我没有弄清楚如何正确编写rootReducer以及在使用ngrx/store时将其放置在何处.

I read the Dan Abramov's answer of How to reset the state of a Redux store?, but I didn't figure out how to write rootReducer correctly and where to put it when using ngrx/store.

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

Or is there any other way to handle this in ngrx/store?

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

推荐答案

此答案特定于ngrx版本2.问题还有另一个,最新的答案,说明了如何使用ngrx版本4进行同样的操作.

This answer is specific to ngrx version 2. The question has another, more recent answer that explains how the same can be done with ngrx version 4.

compose构建ngrx root reducer .

传递给compose的参数是返回减速器的函数-由减速器组成,它们本身作为参数传递.您可以像这样对商店进行重置:

The arguments passed to compose are functions that return a reducer - composed from the reducer they themselves are passed as an argument. You can compose the resetting of your store like this:

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.如果那不是您想要的,则可以调整示例.

Note that this will reset all of the store's state - including the router. If that's not what you want, you could tweak the example.

随着NgModule的引入,引导程序已更改,但是您仍将组成的减速器传递给provideStore:

With introduction of NgModule the bootstrapping has changed, but you still pass the composed reducer to provideStore:

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

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

这篇关于如何重置ngrx/store的所有状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆