0

我正在尝试使用 mobx-state-tree 创建一个超级简单的嵌套存储,但我不知道如何让它工作。要么这个库非常不直观,要么我只是遗漏了一些明显的东西。我试着把所有东西都包起来MST.types.optional(),看看是否有区别,但没有。

这个想法是 Orders 商店有许多买卖订单。我想创建一个没有任何订单的空商店。

当我尝试执行 Orders.js 时,我收到以下错误:

Error: [mobx-state-tree] Error while converting `undefined` to `map<string, AnonymousModel>`: value `undefined` is not assignable to type: `map<string, AnonymousModel>` (Value is not a plain object), expected an instance of `map<string, AnonymousModel>` or a snapshot like `Map<string, { timestamp: Date; amount: number; price: number }>` instead.`

order.js

const MST = require("mobx-state-tree")

const Order = MST.types.model({
    timestamp: MST.types.Date,
    amount: MST.types.number,
    price: MST.types.number,
}).actions(self => {
    function add(timestamp, price, amount) {
        self.timestamp = timestamp
        self.price = price
        self.amount = amount
    }
    return { add }
})

module.exports = Order

订单.js

const MST = require("mobx-state-tree")
const Order = require('./order')

const Orders = MST.types.model({
    buys: MST.types.map(Order),
    sells: MST.types.map(Order),
}).actions(self => {
    function addOrder(type, timestamp, price, amount) {
        if(type === 'buy'){
            self.buys.add(timestamp, price, amount)
        } else if(type === 'sell') {
            self.sells.add(timestamp, price, amount)
        } else throw Error('bad order type') 
    }
    return { addOrder }
})
Orders.create()
4

1 回答 1

1

是的,您需要将所有内容包装为 types.optional 并为此提供默认快照。这是一个例子

const MST = require("mobx-state-tree")
const Order = require('./order')

const Orders = MST.types.model({
    buys: MST.types.optional(MST.types.map(Order), {}),
    sells: MST.types.optional(MST.types.map(Order), {}),
}).actions(self => {
    function addOrder(type, timestamp, price, amount) {
        if(type === 'buy'){
            self.buys.add(timestamp, price, amount)
        } else if(type === 'sell') {
            self.sells.add(timestamp, price, amount)
        } else throw Error('bad order type') 
    }
    return { addOrder }
})
Orders.create()

types.optional 在幕后做的是拦截未定义并将其替换为您的默认值:)

于 2017-10-22T07:08:29.780 回答