angular - 带有 ngrx/effects 的无限循环

标签 angular redux side-effects ngrx

我正在尝试了解 ngrx/effects。我构建了一个简单的函数,每次单击都会将数字递增 1。但是单击时它会进入无限循环,不确定发生了什么。我确定我犯了一些愚蠢的错误。

monitor.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 ) {};
}

监控组件.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 允许您观察给定的 Action 类型并在每次分派(dispatch)时对该 Action 使用react。

因此,如果您观察某个效果中的 Action X 并从该效果中分派(dispatch)另一个 Action X,您将陷入无限循环。

在你的情况下:你的 Action 是 .ofType(monitor.ActionTypes.INCREMENT) 类型,然后从你的效果中派发一个 Action monitor.ActionTypes.INCREMENT (从这部分我假设:monitor.IncrementAction(payload+1)),然后效果被再次触发,一次又一次,...

关于angular - 带有 ngrx/effects 的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40923738/

相关文章:

html - 滚动条导致 Microsoft Edge 中的表格未对齐

javascript - 获取数组中的本地存储值

javascript - 如何在 react-redux 中使用扩展运算符修改索引处的特定对象?

javascript - 如何为相同数据类型的多个实例重用 Redux reducer 逻辑?

reactjs - shouldComponentUpdate 是否会阻止连接的子组件更新

Java:为什么这个方法有副作用?

angular - SafeValue 必须使用 [property]=binding 虽然我已经在使用属性绑定(bind)

angular - 导入 Angular 组件以在所有模块中可用

javadoc - 如何记录 Java 副作用

haskell - 如果你编译一个没有输入的程序会发生什么? (Haskell IO 纯度问题(再次))