我有一个start
和end
属性,它在我的state
中存储一个日期。任何时候状态的其他部分得到改变,我的subscription
为start
和end
日期被触发。
这是我的订阅
this.subs.sink = this.store
.select(fromTransactionReducer.selectStartAndEndDate)
.subscribe((date) => {
console.log("range", date);
this.range.setValue({
start: date.start,
end: date.end,
});
});
这是选择器
export const selectStartAndEndDate = createSelector(
selectTransactionState,
(state) => ({ start: state.start, end: state.end })
);
这是dateRange减速器
on(transactionActions.UpdateDateRange, (state, { start, end }) => ({
...state,
start,
end,
})),
这是日期范围操作
export const UpdateDateRange = createAction(
"[Transaction Page] Update Date Range",
props<{ start: Date; end: Date }>()
);
这是我的状态
export interface State {
transaction: Transaction[];
cursors: Cursor;
totalTransactions: number;
loading: boolean;
errorMessage: string;
formErrorMessage: string;
items_per_page: number;
pageSizeOptions: number[];
pageIndex: number;
searchKey: string;
formMessage: string;
start: Date;
end: Date;
trans_type: string;
base_type: string;
}
export const initialState: State = {
transaction: [],
cursors: {
after: "",
before: "",
hasNext: false,
hasPrevious: false,
},
totalTransactions: 0,
loading: false,
errorMessage: null,
formErrorMessage: null,
items_per_page: 5,
pageSizeOptions: [2, 3, 5, 10, 15],
pageIndex: 0,
searchKey: "",
formMessage: "",
start: null,
end: null,
trans_type: null,
base_type: null,
};
任何时候我调度不同的action
,例如this.store.dispatch(transactionActions.ResetPageIndex());
,我的subscription
日期被触发。
为什么?
在我的减速器中,当UpdateDateRange
动作被调度时,我只更新start
和end
日期。
ngrx的select
操作符使用rxjs的distinctUntilChanged
操作符来确保选择器只有在其结果发生变化时才会发出。参考源代码在这里:https://github.com/ngrx/platform/blob/a6fe92df3134b7a589a2e95abe0aea183b411f03/modules/store/src/store.ts#L249
默认distinctUntilChanged
使用相等比较器(参见https://www.learnrxjs.io/learn-rxjs/operators/filtering/distinctuntilchanged),并注意'对象引用必须匹配!'
selectStartAndEndDate
选择器-它返回一个对象.此外,它返回一个新实例对象每次执行时的。正因为如此,distinctUntilChanged
中的比较总是失败,所以选择器总是发出。
如何解决:
// returned date will be considered equal next time so selector won't fire
export const selectStartDate = createSelector(
selectTransactionState,
(state) => state.start
);
// same here
export const selectEndDate = createSelector(
selectTransactionState,
(state) => state.end
);
// as input selectors didn't change, this won't fire either
export const selectStartAndEndDate = createSelector(
selectStartDate,
selectEndDate ,
(start, end) => ({ start, end })
);
Stackblitz: https://codesandbox.io/s/so-ngrx-selector-emit-1zxg1?file=/src/app/store/selectors.ts