NGXS中无自有属性的含子状态的StateModel该如何定义?
无自有属性的父状态 StateModel 处理方案
有两种常用的处理方式,可根据项目实际需求选择:
方案1:直接使用空接口(轻量化,适合纯容器场景)
父状态仅作为子状态的挂载容器、不需要做额外类型校验的情况下,直接定义空接口作为泛型参数即可,不需要配置defaults属性:
// 定义空接口作为纯容器父状态的模型 export interface SomeStateModel {} @State<SomeStateModel>({ name : 'someState', children : [ ThingAState, ThingBState, ThingCState ] }) @Injectable() export class SomeState{}
方案2:组合子状态模型(类型安全,适合大型项目)
如果需要在使用选择器时获得完整的类型提示,可将所有子状态的模型组合到父状态的模型中:
// 先引入各个子状态的模型定义 import { ThingAStateModel } from './thing-a.state'; import { ThingBStateModel } from './thing-b.state'; import { ThingCStateModel } from './thing-c.state'; export interface SomeStateModel { // 键名必须和对应子状态@State装饰器里的name属性完全一致 thingA: ThingAStateModel, thingB: ThingBStateModel, thingC: ThingCStateModel } @State<SomeStateModel>({ name : 'someState', children : [ ThingAState, ThingBState, ThingCState ] }) @Injectable() export class SomeState{}
注意:该方案下如果后续新增/删除子状态,需要同步更新父状态的模型定义,避免出现类型不匹配的问题。
嵌套纯容器状态的处理
如果要把上述SomeState作为另一个无自有属性的上层状态的子状态,处理逻辑完全一致,示例如下:
// 空接口写法示例 export interface RootContainerStateModel {} @State<RootContainerStateModel>({ name: 'rootContainer', children: [SomeState] }) @Injectable() export class RootContainerState {} // 类型安全组合写法示例 import { SomeStateModel } from './some.state'; export interface RootContainerStateModel { someState: SomeStateModel } @State<RootContainerStateModel>({ name: 'rootContainer', children: [SomeState] }) @Injectable() export class RootContainerState {}
内容的提问来源于stack exchange,提问作者Optiq
相关产品推荐
相关产品推荐

