繁体   English   中英

带有ngrx/效果的无限循环

[英]Infinite loop with ngrx/effects

我试图了解ngrx/效果。 我构建了一个简单的函数,每次单击都会将 number 递增 1。 但是点击时它会无限循环,不知道发生了什么。 我确定我犯了一些愚蠢的错误。

监视器.effects.ts

@Injectable()
export class MonitorEffects {
    @Effect()
    compute$: Observable<Action> = this.actions$
        .ofType(monitor.ActionTypes.INCREMENT)
        .map((action: monitor.IncrementAction) => action.payload)
        .switchMap(payload => {
            return this.http.get('https://jsonplaceholder.typicode.com/users')
             .map(data => new monitor.IncrementAction(payload+1))
             .catch(err => of(new monitor.InitialAction(0)))
        });

    constructor(private actions$: Actions, private http:Http ) {};
}

monitor.component.ts

ngOnInit() {
    this.storeSubsciber = this
      .store
      .select('monitor')
      .subscribe((data: IMonitor.State) => {
        this.value = data.value;
        this.errorMsg = data.error;
        this.currentState = data.currentState;
      });
  }

  increment(value: number) {
    this.store.dispatch(new monitorActions.IncrementAction(value));
  }

监视器.reducer.ts

export const monitorReducer: ActionReducer<IMonitor.State> = (state = initialState, action: Actions) => {
  switch (action.type) {
    case ActionTypes.INCREMENT:
      return Object.assign({}, { value: action.payload, currentState: ActionTypes.INCREMENT, error: null });
...
...
...

    default:
      return Object.assign({}, { value: 0, currentState: ActionTypes.INITIAL, error: null });
  }
}

Effect允许您观察给定的动作类型,并在每次调度该动作时对该动作作出反应。

因此,如果您在某个效果中观看动作 X 并从该效果中分派另一个动作 X,您将最终陷入无限循环。

在您的情况下:您的操作属于.ofType(monitor.ActionTypes.INCREMENT)类型,然后根据您的效果调度一个操作monitor.ActionTypes.INCREMENT (从这部分我假设: monitor.IncrementAction(payload+1) ),然后效果被再次触发,一次又一次,......

我也遇到了同样的问题,答案是我的效果并没有返回与当前效果键控完全不同的动作。

为了我的影响,我只做了一个.do() ,并没有 switchMap 它到一个新的动作。 那是我的问题。 因为我不需要触发新动作,所以我做了一个 NoopAction 来获得回报。 这意味着任何人都不应该在减速器中使用 NoopAction。

我遇到了这个问题,这里的答案没有帮助。 对我来说,我有一个“成功”的动作,它有一个tap()来导航。 我的浏览器会锁定,我不明白为什么,直到我在我的点击功能中输入一个日志并注意到它被无限击中。

我的问题是,当tap返回相同的 observable 时,效果会自动调用。 我错过了什么,我的解决方案......将dispatch: false放在我的效果上,以防止它自行调度。

@Effect({dispatch: false})

我们已经从马克西姆那里得到了正确的答案

我来这里是为了同样的问题,但没有任何效果,就我而言,这是复制粘贴问题

export const LoadCustomers = createAction(
    '[Customers] Load Customers' 
)
export const LoadCustomers_Success = createAction(
    '[Customers] Load Customers',
    props<{customers: Array<ICustomer>}>()
)
export const LoadCustomers_Failure = createAction(
    '[Customers] Load Customers',
    props<{error: string}>(),
)

我的错误是类型'[Customers] Load Customers' ,我更改了操作名称但忘记更改类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM