@ngrx/entitiy 选择器在更改自定义状态时不会触发

@ngrx/entitiy selector doesn't fire when changing custom state

我扩展了一个@ngrx/entity 状态存储以包含应从服务器检索的实体的加载值。

const adapter = createEntityAdapter<A>();
export interface AState extends EntityState<A> {
  loading: {
    projects: {
      [id: string]: boolean
    },
    collections: {
      [id: string]: boolean
    }
  };
}
const initialState: AState = adapter.getInitialState({
  loading: {
    projects: {},
    collections: {}
  }
});

为了能够显示这个加载值,我使用了这个选择器:

export const getRunsLoadingByProject = createSelector(
  (state: AppState) => state.a,
  (state: AState, Id: number) => {
    return !!state.loading.projects[Id];
  }
);

这在第一次加载时效果很好。实体和加载值得到更新,选择器就像一个魅力。问题发生在网站上我需要的 'update' 按钮上。一旦来自服务器的实体状态与商店中已有的状态相同,选择器就会停止检索新的加载状态。 使用 devtools 我可以看到状态以正确的方式改变(加载标志设置为 true 然后 false)。

它似乎只是选择器。这是@ngrx/entities 的一个怪癖,即选择器仅在实体更改时触发吗?还是我遗漏了什么?

编辑:Reducer

export function aReducer(state: AState = initialState, action: AEffectsActions): RunState {
  switch (action.type) {
    case AEffectsActionTypes.LOAD_RUN: {
      const newState = { ...state };
      newState.loading.projects[action.payload.toString()] = true;
      return newState;
    }
    case AEffectsActionTypes.LOAD_RUN_SUCCESS: {
      const newState = adapter.addMany(action.runs, state);
      newState.loading.projects[action.projectId] = false;
      return newState;
    }
    default:
      return state;
  }

} 

扩展运算符仅在顶层 "clones",您的选择器未被执行,因为对 loading.projects 的引用仍然相同。

因此您必须执行以下操作。

return {
   ...state,
   loading: {
      ...state.loading,
      projects: {
        ...state.loading.projects,
        [action.payload.toString()]: true
      }

   }
};