商店与商店<T>

Store vs Store<T>

我几乎是 redux 模式的新手并且刚刚开始使用 ngrx。它很棒,我想尽可能多地使用它,但我有几个关于 Store 概念的问题。

我将尝试通过一些示例来描述问题,并在本篇文章的最后提出我的问题 post。

让我们从 AppState 接口和缩减器开始:

export interface AppState{
   people: Person[],
   events: Event[]
}

//events reducer
export function eventsReducer(state: any = {}, {type, payload}): Event[]{
  switch(type){
    case "ADD_EVENT":
      return [...state, payload];
    default:
      return state;
  }
}

//people reducer
export function peopleReducer(state: any = {}, {type, payload}): Person[]{
  switch(type){
    case "ADD_PERSON":
      return [...state, payload];
    default:
      return state;
  }
}

//root reducer
const root: ActionReducer<AppState> = combineReducers({people: peopleReducer, events: eventsReducer});
const INITIAL_STATE = {
   people:[],
   events: []
}
export function rootReducer(state: any = INITIAL_STATE, action: any){
   return root(state, action);
}

rootReducer是这样加的:

//part of the AppModule
...
imports:[
...,
StoreModule.provideStore(rootReducer)
]

主要 AppComponent 这是我访问 store:

的方式
//part of the AppComponent
export class AppComponent{
   people: Observable<Person[]>;
   events: Observable<Event[]>;

   constructor(private store: Store<AppState>){
      this.people = store.select('people');
      this.events = store.select('events');
   }
}

现在,一切正常,我真的很喜欢这个概念,但我注意到,如果我从 AppState 界面中删除其中一个属性(例如,我删除people 属性,其他一切保持不变。

所以我想知道使用 Store<AppState> 而不仅仅是 Store 的主要原因是什么以及使用 Store<AppState> 的主要优点是什么(它实际上是与仅使用 Store) 的区别?此外,有没有一种方法可以在 AppState 更改时至少强制执行运行时错误,但其他一切保持不变?

我用错的可能性也很大,不过还是想知道这些问题的答案

商店的 select method 可以传递一个或多个 属性 字符串或选择器函数。

当传递 属性 个字符串时,它的行为类似于 pluck. And when passed a selector function, it behaves like map

它们之间的显着区别是传递给 pluck 的 属性 路径无法进行类型检查,而 pluck returns Observable<any>,所以状态的类型信息基本上丢失了。

如果您使用选择器函数,您将看到缺少属性等的 TypeScript 错误。

例如,这个:

store.select(state => state.missing);

会产生错误,而这不会:

store.select('missing');