MST:用自身的 children 定义模型
MST: define model with children of itself
刚开始fiddle Mobx-state-tree。
我有这个模型,它具有 parent
和 children
属性,可以用同一模型的实例填充。
所以基本上是这样的:
const Page = types.model({
guid: types.string,
title: types.string,
description: types.string,
parent: types.union(Page, types.undefined),
children: types.array(Page),
})
但是,显然 Page
尚无法创建此模型。
我该怎么做?
仔细阅读文档后,我找到了答案。使用 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)), []),
})
刚开始fiddle Mobx-state-tree。
我有这个模型,它具有 parent
和 children
属性,可以用同一模型的实例填充。
所以基本上是这样的:
const Page = types.model({
guid: types.string,
title: types.string,
description: types.string,
parent: types.union(Page, types.undefined),
children: types.array(Page),
})
但是,显然 Page
尚无法创建此模型。
我该怎么做?
仔细阅读文档后,我找到了答案。使用 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)), []),
})