我正在尝试了解 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/