为什么一定要 ngrx / redux effects return 动作?使用像 elm 这样的 noop 动作是否被认为是不好的做法?

Why must must ngrx / redux effects return actions? Is using a noop action like elm considered bad practice?

我正在使用 Angular、ngrx/store 和 ngrx/effects 的 redux 风格的状态管理设计。每当我不 return 一个效果的动作时,我都会收到一个错误:

Cannot read property 'type' of undefined

我研究了这个问题,发现在 elm 架构中有一个叫做 "noop" 的动作,当您不想将另一个动作与您的效果链接时,您可以调用它什么都不做。到处调用这个 noop 动作对我来说似乎非常重复。我想知道这是否是一个不好的做法。有什么理由不能产生不 return 动作的效果?效果的意图是否总是让 1 个动作触发另一个动作?我想知道我是否误解了如何使用效果。

谢谢!

默认情况下,ngrx/effect 调度一个动作。

如果您希望效果为 'fire-and-forget',您需要做的就是将 {dispatch: false} 作为参数添加到 @Effects() 装饰器。

来自@ngrx/effects docs

Observables decorated with the @Effect() decorator are expected to be a stream of actions to be dispatched. Pass { dispatch: false } to the decorator to prevent actions from being dispatched.

Usage:

class MyEffects {
  constructor(private actions$: Actions) { }

  @Effect({ dispatch: false }) logActions$ = this.actions$
    .do(action => {
      console.log(action);
    });
}

在幕后,这是通过 ignoreElements operator. (Here 实现的 ngrx/effect 的源代码,如果您有兴趣的话)。 ignoreElements 每次效果运行时都有一个 built in noop function that gets called

简而言之,在 ngrx/effects 中不需要显式的 noop-action。我不会直接称它为 'bad practice' 来发送 noop-action,但在使用 ngrx 时肯定没有必要。