首页 > 解决方案 > MST:用自己的孩子定义模型

问题描述

刚开始摆弄 Mobx-state-tree。

我有这个模型,它具有可以用同一模型的实例填充的属性 parentchildren

所以基本上是这样的:

const Page = types.model({
    guid: types.string,
    title: types.string,
    description: types.string,
    parent: types.union(Page, types.undefined),
    children: types.array(Page),
})

但是,显然Page还没有创建这个模型。

我怎样才能做到这一点?

标签: mobx-state-tree

解决方案


在仔细阅读文档后,我找到了答案。使用types.late()

const Page = types.model({
    guid: types.string,
    title: types.string,
    description: types.string,
    parent: types.union(types.late(() => Page), types.undefined),
    children: children: types.optional(types.array(types.late(() => Page)), []),
})

推荐阅读