代码之家  ›  专栏  ›  技术社区  ›  Maryannah

ngrx:状态接口的密钥和storemodule.forroot的密钥之间的差异

  •  2
  • Maryannah  · 技术社区  · 7 年前

    我刚开始使用NGRX,我面临一个小问题。

    我想知道接口状态和模块的键之间的区别 forRoot .

    export interface ConfigurationState {
      readonly configuration: Configuration;
    }
    
    StoreModule.forRoot({
      configuration: ConfigurationReducer,
    }),
    
    export function configurationReducer(state: Configuration = undefined, action: ConfigurationActions.Actions): Configuration {
      switch (action.type) {
        case ConfigurationActions.SET:
          return action.payload;
        default:
          return state;
      }
    }
    
    this.store.select('configuration')
    

    当我用第4段代码选择一个商店时,我看到第一段代码的键的IntelliSense帮助。

    如果我更改第二段代码的键,它不会更改任何内容。

    所以我的问题是,目的是什么 福根 ?钥匙重要吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   timdeschryver    7 年前

    Inerface的工作是排版检查和一些智能感知。这个 forRoot 注册你的减速器,这是最重要的部分,否则你的减速器不会被调用。

    在示例中,您发布 State 接口实际上并没有添加任何值,但如果按如下方式进行,它会添加一些类型检查值。

    // reducer.ts
    
    /**
     * As mentioned, we treat each reducer like a table in a database. This means
     * our top level state interface is just a map of keys to inner state types.
     */
    export interface State {
      layout: fromLayout.State;
      router: fromRouter.RouterReducerState;
    }
    
    /**
     * Our state is composed of a map of action reducer functions.
     * These reducer functions are called with each dispatched action
     * and the current or initial state and return a new immutable state.
     */
    export const reducers: ActionReducerMap<State> = {
      layout: fromLayout.reducer,
      router: fromRouter.routerReducer,
    };
    
    
    // app.module.ts
    StoreModule.forRoot(reducers),
    

    取自 NgRx example app

    推荐文章