網站搜尋

angular - 當功能切片為空時的 NgRx 選擇器


在我的應用程式中,有一個帶有功能切片的商店:

@NgModule({
    imports: [
    CommonModule,
    TranslateModule.forChild({}),
    StoreModule.forFeature('slice', slice)
    ...
})

功能的縮減器映射:

export const slice: ActionReducerMap<SliceState> = {
    someReducer
};

以及特徵選擇器:

export const selectSliceModule = createFeatureSelector<SliceState>('slice');
export const selectItem = createSelector(selectSliceModule,
(state: SliceState) => state.someReducer.paramA);

有一個登出操作,在登出後會清除主存儲以及 slice,所以登出後 slice === null。

元件訂閱了功能商店切片,使用選擇器 selectItem,然後失敗,因為 state.someReducer 為 null:state.someReducer.paramA。

我的問題是:在這種情況下在選擇器中使用三元運算符可以嗎?這會破壞選擇器的記憶化嗎?還是有更好的方法來處理這種情況?

// Is it OK to have ternary operator in selector?
export const selectItem = createSelector(selectSliceModule,
(state: SliceState) => state.someReducer ? state.someReducer.paramA : null);

答案#1

我遇到了這個問題,然後意識到我對受影響狀態部分的 reducer 在其 switch 語句中沒有返回傳遞給 reducer 函數的狀態的默認情況。沒有那個默認情況,reducer 返回的初始狀態是未定義的。增加默認狀態解決了我的問題。希望這也能幫助到你。

答案#2

我知道這個問題很舊,但也許這可以幫助到某人。

遇到相同的問題,原因是我的元件在被銷毀後還試圖存取資料。

添加 takeUntil 解決了我的問題

this.restaurantData$ = this.restaurantQuery$
      .pipe(
        takeUntil(this._ngOnDestroy), // Added this line
        filter((restaurantQuery) => !!restaurantQuery),
        switchMap((restaurantQuery) => restaurantQuery.valueChanges),
        map((response) => response.data.vendor)
      ); 

現在登出後,組件停止監聽選擇器。