在Angular 10中使用NgRx时,如果以数组作为存储属性,并且在先前状态中始终为空,可能需要进行一些调整才能正常使用。以下是一个解决方法,包含代码示例:
export interface AppState {
items: Item[]; // items为存储属性,类型为Item数组
}
export const initialState: AppState = {
items: [] // 初始化items为空数组
};
import { createReducer, on } from '@ngrx/store';
import { loadItemsSuccess } from './item.actions';
import { initialState } from './item.state';
export const itemReducer = createReducer(
initialState,
on(loadItemsSuccess, (state, { items }) => ({
...state,
items: items // 更新items属性为从action中获取的items数组
}))
);
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { itemReducer } from './item.reducer';
import { ItemEffects } from './item.effects';
@NgModule({
imports: [
StoreModule.forFeature('items', itemReducer),
EffectsModule.forFeature([ItemEffects])
]
})
export class ItemModule { }
通过上述步骤,可以确保以数组作为存储属性的先前状态始终为空。这样,当相关的action被触发时,可以正确地更新存储属性并在应用程序中使用它们。
希望这个解决方法对你有帮助!