【问题标题】:Extending a model in mobx state tree在 mobx 状态树中扩展模型
【发布时间】:2019-07-01 04:05:00
【问题描述】:

我有一堆商店,每个商店都包含一个实体类型的列表,例如

const userStore = EntityStore.create(....)

const supplierStore = EntityStore.create(....)

有些商店可以提供额外的功能,所以我写了

const orderStore = EntityStore
.views(self => ({
    allByUserId: branchId => ....)
}))
.create(....)

到目前为止,一切都很好,但现在我想创建一个“商店经理”,其中包含所有此类商店的列表,但它失败并显示如下消息

错误:[mobx-state-tree] 转换时出错 ...
EntityStore 类型的值:(id:Order)> 不可分配给类型:EntityStore
期望 EntityStore 的实例或类似 ... 的快照
(请注意,所提供值的快照与目标类型兼容)

消息很清楚,我的“EntityStore with views”与“EntityStore”的类型不同。但它是它的扩展,所以我想知道是否有声明允许它。 Java 中的 List<? extends EntityStore> 之类的东西?

或者是一个不错的解决方法,允许我在不更改其类型的情况下向EntityStore 添加附加功能?

【问题讨论】:

    标签: mobx-state-tree


    【解决方案1】:

    没有。你不能。因为.views()(基本上与任何其他点方法一样)每次调用它时都会创建a whole newModelType 对象。

    你可以做的是使用 union 类型:

    • types.union(options?: { dispatcher?: (snapshot) => Type, eager?: boolean }, types...) 创建多种类型的联合。如果正确 无法从快照中明确推断出类型,请提供 dispatcher 函数来确定类型。当急切标志设置为 true (默认) - 如果设置为 false,将使用第一个匹配类型 只有当 1 个类型完全匹配时,类型检查才会通过。

    下面还有一个simulate inheritance by using type composition的例子:

    const Square = types
        .model(
            "Square",
            {
                width: types.number
            }
        )
        .views(self => ({
            surface() {
                return self.width * self.width
            }
        }))
    
    // create a new type, based on Square
    const Box = Square
        .named("Box")
        .views(self => {
            // save the base implementation of surface
            const superSurface = self.surface
    
            return {
                // super contrived override example!
                surface() {
                    return superSurface() * 1
                },
                volume() {
                    return self.surface * self.width
                }
            }
        }))
    
    // no inheritance, but, union types and code reuse
    const Shape = types.union(Box, Square)
    

    所以,没有继承,但是,联合类型和代码重用

    【讨论】:

      猜你喜欢
      • 2019-02-12
      • 2021-05-03
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多