方案
我有两个模型,一个是Expense,另一个是DailyExpense(包含一个Expense数组),顾名思义,Expense只是Expense中的一个项目,而DailyExpense拥有一大笔费用。
import { types } from 'mobx-state-tree';
/**
* Expense model which holds individual item
*/
export const Expense = types.model({
name:types.string,
price:types.number,
quantity:types.number,
}).actions(self => ({
changeName(newName) {
self.name = newName
},
changePrice(newPrice) {
self.price = newPrice
},
changeQuantity(newQuant) {
self.quantity = newQuant
},
})).views(self => ({
get totalPrice () {
return self.price * self.quantity
}
}))
/**
* DailyExpense model which have arrays of Expense
* Also have date as unique identifier
*/
export const DailyExpense = types.model({
date:types.string,
items:types.optional(types.array(Expense),[])
}).actions(self => ({
changeDate (newDate) {
self.date = newDate
},
addItem (newItem) {
self.items.push(newItem)
},
removeItem (name) {
const index = self.items.findIndex(e => {
if(e.name === name)
return e
})
self.items.splice(index,1)
}
})).views(self => ({
get totalPrice () {
return self.items.reduce((sum,entry) => sum+(entry.price * entry.quantity),0)
}
}))
问题
是否可以创建一个模型来跟踪我的所有DailyExpense
我知道我可以创建另一个模型,我可以做这样的事情
export const ExpenseList = types.model({
list:types.array(DailyExpense)
})
但是我可以在没有任何变量的情况下创建模型,就像这里没有列表一样吗?(我知道这样做不行,我试过了)
export const ExpenseList = types.model(types.array(DailyExpense))
我尝试过创建以下模型
export const ExpenseList = types.model(types.array(DailyExpense))
.actions(self => ({
add (s) {
self.push(s);
}
}))
我运行以下测试用例,但它给了我一个错误[mobx-state-tree] Functions are not supported as properties, use views instead
it ('can add in list', () => {
const dailyExpense = DailyExpense.create ({
date: today,
items: [
{name: 'First Item', price: 20, quantity: 4},
{name: 'Second Item', price: 10, quantity: 2},
{name: 'Third Item', price: 5, quantity: 1}
],
});
const expenseList = ExpenseList.create(dailyExpense);
expect(expenseList.length).toBe(1);
});
答案 0 :(得分:0)
不,目前不支持:)