简体   繁体   English

如何修改NGR存储不在reducer中?

[英]How to modify NGRX store not in reducer?

In the code I have something like: 在代码中,我有类似以下内容:

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

this action is handled by one of the @Effect and fires new LoadGameSuccess(game) . 此动作由@Effect之一处理,并触发new LoadGameSuccess(game) Than this game is passed to reducer to update GameState . 比此游戏还传递给reducer更新GameState However how can I change the GameState to reflect that game is currently being loaded? 但是,如何更改GameState以反映当前正在加载游戏? Making one more action and handle it in the reducer looks not very good. 再执行一个动作并在减速器中处理它看起来不是很好。 The application becomes 'actions-hell'... Should I do this in the @Effect ? 该应用程序变为“动作-地狱” ...我应该在@Effect执行此@Effect吗?

Don't try to go against the design pattern. 不要试图违背设计模式。 It's designed that way for a reason. 之所以这样设计是有原因的。

If you have an action that may or may not impact the state of the store based on some other logic, the right way to do it is have an effect that listens for the action, performs the logic, and then dispatches a new action. 如果您基于某个其他逻辑执行的某项操作可能会或可能不会影响存储状态,那么正确的操作方法就是监听该操作,执行该逻辑,然后分派新操作。

That being said - there's no reason you can't handle the LoadGame action in both the store and the effect. 话虽如此-您没有理由在商店和效果中都无法处理LoadGame动作。 Something like this: 像这样:

Your effect 你的效果

@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()]
        )
    )
);

Your Reducer 您的减速机

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,
      };
    }
}

Note that there is no concern for a race condition in doing this . 请注意, 执行此操作无需担心竞争状况

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

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