当 NgRx 中状态的其他部分发生变化时,数组订阅就会被触发

问题描述 投票:0回答:1

我有

locations
activeLocationsIds
数组。
locations
数组包含所有位置,
activeLocationsIds
包含来自活动位置的ID(不是对象,仅是带有
locations
ID的1..1的ID)。

只要状态的其他部分发生变化,例如 selectedOrder,就会触发

activeLocationsIds
的订阅。

这就是我的状态:

export interface ICustomerHierarchyState {
    locations: ILocation[],
    activeLocationsIds: string[];
    selectedOrder: number;
}

这些是用于获取 activeLocations 的选择器:

export const getActiveLocationsIds = createSelector(
    getCustomerHierarchyState,
    state => state.activeLocationsIds
)

export const getActiveLocations = createSelector(
    getCustomerHierarchyState,
    getActiveLocationsIds ,
    (state, getActiveLocationsIds ) => state.locations.filter(x => getActiveLocationsIds.includes(x.locationId)) ?? []
)

这是 activeLocationsIds 减速器:

on(CustomerHierarchyPageActions.setActiveLocations, (state, action): ICustomerHierarchyState => {
        return {
            ...state,
            activeLocationsIds: action.locationsIds
        }
    })

这是

activeLocationsIds
动作:

export const setActiveLocations = createAction(
    '[Customer-Hierarchy Page] Set ActiveLocations',
    props<{ locationsIds: string[] }>()
)

还有,这里是清理用的减速机

selectedOrder

on(CustomerHierarchyPageActions.clearSelectedOrder, (state): ICustomerHierarchyState => {
        return {
            ...state,
            selectedOrder: -1
        }
    })

最后,这是

getActiveLocations
订阅:

this.subscriptions.add(
      this.store.select(getActiveLocations)
        .subscribe(
          activeLocations => {
            this.activeLocations = activeLocations;
          }
        ));

每当我发送不同的操作(例如

this.store.dispatch(CustomerHierarchyPageActions.clearSelectedOrder());
)时,都会触发对
activeLocations
的订阅。

这是为什么?

在我的减速器中,我只更新

selectedOrder
(到-1值),所以我不知道为什么
getActiveLocations
订阅被触发...

angular typescript redux ngrx ngrx-store
1个回答
0
投票

这是您的答案:当减速器更改切片时,Ngrx 选择器不会触发

此检查是一个简单的参考检查(===)。因为你正在修改 直接状态,引用保持不变

您正在创建一个新对象,这意味着一个新引用

© www.soinside.com 2019 - 2024. All rights reserved.