选择器订阅未调用

时间:2019-03-21 13:38:58

标签: ngxs

有人可以解释究竟何时调用selector订阅吗?我以前的理解是,每当减速器更改state(创建一些差异)时,就会调用selector。但是在下面的代码中,它没有发生。

调度SaveVersionSuccess时未调用以下选择器(A行)。在减速器中,我将state.version.versions[0].updated_fields.workflowtrue更改为false

有人可以解释为什么吗? {{3}}

@Select(state => state.version.versions) version$: Observable<any[]>;
ngOnInit(): void {
    this.version$.subscribe((versions) => {//line A
      alert()
    });
  }


  test(){
    this.store.dispatch([
      new SaveVersionSuccess({bot:null, version:{id: 1, updated_fields:{'workflow':false}}})
    ]);

减速器

  @Action(SaveVersionSuccess)
  SaveVersionSuccess({patchState, setState, getState, dispatch,}: StateContext<ICodeInputState>, {payload}: SaveVersionSuccess) {
    let state = getState();
    let index = state.versions.findIndex((version) => version.id === payload.version.id);
    let index_pristine = state.versions_pristine.findIndex((version) => version.id === payload.version.id);

    state.versions[index] = {
      ...payload.version
    };
    state.versions_pristine[index_pristine] = {
      ...payload.version
    };
    patchState({...state});
}

初始状态

const codeInputState: ICodeInputState = {
  versions: [{id: 1, updated_fields:{'workflow':true}}],
  versions_pristine: [{id: 1, updated_fields:{'workflow':true}}]
};

1 个答案:

答案 0 :(得分:0)

正如评论所建议的那样,修补状态时看起来像是不可变性的问题,原始方法是修改现有状态,而不是修补新状态。

我在您的StackBlitz上尝试了此版本,似乎可以正常运行,

@Action(SaveVersionSuccess)
  SaveVersionSuccess({patchState, setState, getState, dispatch,}: StateContext<ICodeInputState>, {payload}: SaveVersionSuccess) {
    let state = getState();
    let index = state.versions.findIndex((version) => version.id === payload.version.id);
    let index_pristine = state.versions_pristine.findIndex((version) => version.id === payload.version.id);

    // Create a new versions array
    const versions = [...state.versions];
    // Patch the value at the required index
    versions[index] = payload.version;

    // Create a new versions_pristine array
    const versions_pristine = [...state.versions_pristine];
    // Patch the value at the required index
    versions_pristine[index_pristine] = payload.version;

    // Patch the state with the new arrays    
    patchState({
      versions: versions,
      versions_pristine: versions_pristine
    });
  }