Redux-Angular:如何防止两次调用动作? [英] Redux - Angular: How prevent actions called twice?

查看:58
本文介绍了Redux-Angular:如何防止两次调用动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Redux这是一个非常酷的库,我真的很喜欢它,但是如何防止两次调用该动作呢?哪些错误会导致这种行为?考虑到我已经取消了订阅到控制器中

Redux It's a very cool library, I really like it, but how can I prevent that actions call twice? What mistakes can generate this behavior ? Consider that I've already unsubscribe the subscription into the controller

constructor(private _store: Store<AppState>) {
    this.subscription = this._store.select('reduxObj').subscribe(function (item) {
      switch (item.type) {
        case fromAction.GETITEMS: {
          break;
        }
      }
    }.bind(this));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }


  ngOnInit() {
    this._store.dispatch(new fromAction.GetListAction());
  }



    //REDUCER
    export function ReduxReducer(state: any = undefined, action: fromAction.actions) {

  switch (action.type) {
    case fromAction.GETITEMS: {
      return { ...state, type: fromAction.GETITEMS }
    }
  }


  //ACTION
  export class GetListAction implements Action {
    readonly type = GETITEMS;
    constructor() { }
  }

推荐答案

人们似乎专注于琐碎的事情.

People seem to focus on trivial things.

所以我将直接回答您的问题:

So I'll straight answer your question :

商店中的 select 以其最简单的实现侦听 dispatch 事件.

a select on a store listens to dispatch events in its most simple implementation.

您调用 dispatch 两次,您的订​​阅被调用两次.

You call dispatch twice, your subscription gets called twice.

现在这可以随效果等改变,但我假设您没有.

Now this can change with effects and so on, but I'll assume you don't have any.

如果两次被调用,那是因为您的商店已使用默认值实例化.在减速器中的签名是

If it gets called twice, it's because your store is instantiated with a default value. In your reducers signature is

(state: MyState, action: MyAction implements Action) => any

通常,您这样说

myReducer(state: MyState = undefined, action: MyAction implements Action) { ... }

这意味着您的第一个值为 undefined ,如果您调用dispatch,则第二个值为已定义.

This means that you have your first value being undefined, and if you call dispatch, your second value is defined.

这是两个电话打来的地方.

That's where the two calls come from.

此外,您可以将其保留在构造函数中,这不会改变该死的事情.

And as a side note, you can leave it in the constructor, that won't change a damn thing.

要忽略第一个值,可以使用 filter skip (不是一次全部,请根据需要选择一个):

To ignore the first value, you can use filter or skip (not all at once, choose one depending on what you want) :

this.subscription = this._store.select('reduxObj').pipe(
  // For an array, will ignore all empty arrays
  filter(value => value.length),
  // For undefined, will ignore all falsy values
  filter(value => !!value),
  // Ignore first value only
  skip(1),
)

这篇关于Redux-Angular:如何防止两次调用动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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