首页 > 解决方案 > 未调用选择器订阅

问题描述

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

当我分派SaveVersionSuccess. 在减速器中,我state.version.versions[0].updated_fields.workflow从更改truefalse

有人可以解释为什么吗?堆栈闪电战

@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}}]
};

标签: ngxs

解决方案


正如评论所暗示的那样,在修补状态时,它看起来像是一个不变性问题,原来是在修改现有状态而不是修补新状态。

我在您的 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
    });
  }

推荐阅读