将undefined转换为map 时出错
问题描述:
我试图用mobx-state-tree创建一个超级简单的嵌套存储,我无法弄清楚如何让它工作。要么这个图书馆非常不直观,要么我错过了一些显而易见的东西。我尝试在MST.types.optional()
中包装所有内容,看看这是否有所作为,但不是。将undefined转换为map <string,AnonymousModel>时出错
这个想法是,订单商店有很多买卖订单。我想创建一个没有任何订单的空商店。
当我尝试执行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()
答
是的,你需要把所有东西都包裹起来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做的是拦截未定义,替换成你的默认值:)
好的,谢谢。要记住要做点皮塔饼,但幸运的是,模特经常不会改变。 – jimmy