You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:36:05