首页 > 解决方案 > NGXS - 从父状态中选择子状态

问题描述

我正在学习 NGXS 并且有一个具有嵌套父/子关系的状态模型,其中有一些父母,每个父母都有自己的一组孩子(和孙子),如下所示:

state: {
    parents: ParentModel[]
}

ParentModel {
    children: ChildModel[]
}

ChildModel {
   grandchildren: GrandChildren[]
}

etc.

但是,当在 redux/flux 实现中对状态进行建模时,上面的示例(据我所知)通常会被规范化。

我希望能够以与状态树的心理模型相匹配的方式访问子孙。我想出的最好方法是按照文档(https://ngxs.gitbook.io/ngxs/concepts/select#lazy-selectors)中的描述创建一个“惰性选择器”

像这样:

export class ChildRecordState {
@Selector()
    static childRecords(state: ChildRecordModel) {
        return (id: number) => state.Records.filter(r => r.parentId === id);
    }
// ...
}

(这里没有孙子的完整示例:https ://stackblitz.com/edit/angular-ngxs-parent-child )。

我确实看到有可以访问的子状态,我可以在父级中使用它创建一个选择器,但这似乎并没有真正改善结果。问题是 - 访问父母的孩子是否有比示例/stackblitz 中显示的更好的模式?

标签: angularngxs

解决方案


推荐阅读