关于sap:SAP-电商云-Spartacus-UI-Store-相关的设计明细

Store

state.ts

定义了和 Site Context 业务相干的 State 数据模型。

定义数据模型的套路是:

export const SITE_CONTEXT_FEATURE = 'siteContext';

export interface StateWithSiteContext {
  [SITE_CONTEXT_FEATURE]: SiteContextState;
}

这是最顶层的 State 模型了。

SiteContextState 蕴含了三个子 State:

export interface SiteContextState {
  languages: LanguagesState;
  currencies: CurrenciesState;
  baseSite: BaseSiteState;
}

以 CurrenciesState 为例,不仅蕴含了 Entities 列表,还蕴含了以后 Active 状态的 Currency:

export interface CurrenciesState {
  entities: CurrencyEntities;
  activeCurrency: string;
}

再定义 Entities 列表:

export interface CurrencyEntities {
  [isocode: string]: Currency;
}

以上就是 Site Context 畛域所需的 State 数据结构。

留神 SITE_CONTEXT_FEATURE 的应用场合,除了本文件定义 feature state 之外,还用在下列两个文件内:

场景1:用来创立 feature selector:

场景2:应用 StoreModule.forFeature 注册 store:

当应用 createSelector 和 createFeatureSelector 函数时,@ngrx/store 会跟踪调用选择器函数的最新参数。 因为选择器是纯函数,所以当参数匹配时能够返回最初一个后果,而无需从新调用选择器函数。 这能够提供性能劣势,特地是对于执行低廉计算的选择器。这种做法称为 memoization.

createFeatureSelector 是返回顶级(Top Level)的 Feature State的便捷办法。 它为状态的特色切片(Feature Slice)返回一个类型化(typed)的选择器函数。

留神 createFeatureSelector 的调用有两种写法。

写法1

下图 2 必须是 1 的一个切片,并且 3 的类型必须和 2 的类型统一:

2 的地位其实就是 result 的地位:

写法2

import { createSelector, createFeatureSelector } from '@ngrx/store';
 
export const featureKey = 'feature';
 
export interface FeatureState {
  counter: number;
}
 
export interface AppState {
  feature: FeatureState;
}
 
export const selectFeature = createFeatureSelector<AppState, FeatureState>(featureKey);
 
export const selectFeatureCount = createSelector(
  selectFeature,
  (state: FeatureState) => state.counter
);

我做过测试,在 SAP 电商云 Spartacus UI 我的项目里,两种写法齐全等价:

能够顺利通过编译:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理