如何修改不在减速器中的 NGRX 存储?

How to modify NGRX store not in reducer?

在代码中我有类似的东西:

this.store.dispatch(new LoadGame(id));

此操作由 @Effect 之一处理并触发 new LoadGameSuccess(game)。然后将此游戏传递给 reducer 进行更新 GameState。 但是,如何更改 GameState 以反映当前正在加载的游戏?多做一个 action 并在 reducer 中处理它看起来不太好。应用程序变为 'actions-hell'... 我应该在 @Effect 中执行此操作吗?

不要试图违背设计模式。它的设计方式是有原因的。

如果您有一个 可能会或可能不会 影响基于其他逻辑的商店状态的操作,正确的方法是产生一个监听的效果动作,执行逻辑,然后分派新动作。

也就是说 - 您没有理由不能在商店和效果中处理 LoadGame 操作。像这样:

你的效果

@Effect()
  loadGame$ = this.actions$.pipe(
    ofType<LoadGame>(GameActions.LoadGame),
    mergeMap(url => this.http.get<Game>("http://wherever.you.get.your.game.data.from")
        .pipe(
            game => [new LoadGameSuccess(game), new AnyOtherActionsHere()]
        )
    )
);

你的减速器

export function reducer(state = initialState, action: GameActions): State {
  switch (action.type) {
    case GameActions.LoadGame:
      return {
        ...state,
        isGameLoading: true,
      };
    case GameActions.LoadGameSuccess:
      const { game } = action.payload
      return {
        ...state,
        game
        isGameLoading: false,
      };
    }
}

注意有no concern for a race condition in doing this.