【问题标题】:ngRx state change getting lostngRx 状态更改丢失
【发布时间】:2018-10-16 04:02:14
【问题描述】:

按照一些示例,我正在尝试管理侧边栏组件的状态(打开/关闭)。我已经定义了一些接口来管理我的状态对象:

export interface AppState {
  readonly layoutState: LayoutState;
}

export interface LayoutState {
  sideBarOpen: boolean;
}

我的组件中有一个实现 LayoutState 接口的局部变量:layout: LayoutState;

我在ngOnInit订阅我的状态:

this.store.subscribe(appState => {
  this.layout = appState.layoutState;
  // (5)
});

我的 UI 中有一个按钮调用包含以下行的函数:this.toggleSideNav(this.layout.sideBarOpen);

toggleSideNav 看起来像这样:

toggleSideNav(currentState: boolean) {
    this.store.dispatch(new LayoutActions.ToggleSidebarAction(currentState)); // (1)
  }

这是我的效果:

@Effect()
  toggleSidebar$ = this.actions$
    .ofType(LayoutActions.TOGGLE_SIDEBAR)
    .switchMap((action: ToggleSidebarAction) =>
      this.layoutService.toggleSidebar(action.payload) // (2)
    )
    .map((layoutState: LayoutState) => {
       // (4)
      return new LayoutActions.ToggleSidebarSuccessAction(layoutState);
    });

这是layoutService.toggleSidebar 函数:

toggleSidebar(currentState: boolean): Observable<LayoutState> {
    const rv = {
      sideBarOpen: !currentState
    };
    // (3) 
    return Observable.of(rv);
  }

这是我在调试时看到的。在位置:

(1) - currentState 是 false - 正如预期的那样

(2) - action.payload 是 false - 正如预期的那样

(3) - rv 是 {sideBarOpen: true} - 正如预期的那样

(4) - layoutState 是 {sideBarOpen: true} - 正如预期的那样

(5) - this.layout 是 {sideBarOpen: false} - !!

为什么状态会在 (4) 和 (5) 之间“丢失”?

【问题讨论】:

    标签: ngrx


    【解决方案1】:

    我忘记了在 Effect 之后,它进入了 Reducer。我的 Reducer 只有这个:

    switch (action.type) {
        case Actions.LOAD_LAYOUT_SUCCESS:
          return action.payload;
        default:
          return state;
      }
    

    我必须为 TOGGLE_SIDEBAR_SUCCESS 消息添加一个案例以发送新状态(包含在有效负载中):

    switch (action.type) {
        case Actions.LOAD_LAYOUT_SUCCESS:
          return action.payload;
        case Actions.TOGGLE_SIDEBAR_SUCCESS:   <--
          return action.payload;               <--
        default:
          return state;
      }
    

    在添加之前,reducer 一直处于默认情况,并返回 state,这是 旧 状态。

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 2022-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多