将`undefined`转换为`map <string,anonymousmodel =“”>`时出错

时间:2017-10-17 07:55:44

标签: javascript node.js mobx mobx-state-tree

我试图用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

orders.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()

1 个答案:

答案 0 :(得分: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()

在场景后面有什么类型的.optional拦截未定义并用你的默认值替换它:)