mobx -state-tree中的代理

问题描述 投票:0回答:1

我正在尝试构建一个简单的预算应用。每当我将此模型插入我的应用程序时。我得到费用的代理。我的思想缺陷在哪里?

我对Budget.js有操作当我在useEffect中打印它时,这是console.log输出的代理费用。我希望它能从初始状态打印实际数据。


React.useEffect(() => {
    budget.addDummyData()
    console.log(budget.expenses)
  }, [])


[[Handler]]: Object
[[Target]]: Array(0)
[[IsRevoked]]: false


//////////////////////////////////////////////////////////////////////
//SubCategory
const SubCategory = types
  .model('SubCategory', {
    id: types.maybeNull(types.string, ''),
    name: types.maybeNull(types.string, ''),
    amount: types.maybeNull(types.number, 0)
  })
const SubCategoryStore = types.model({ subCategory: types.optional(SubCategory, {}) })
export default SubCategoryStore
/////////////////////////////////////////////////////////////////////////
//Category.js
const Category = types
  .model('Category', {
    id: types.maybeNull(types.string, ''),
    name: types.maybeNull(types.string, ''),
    subCategories: types.array(SubCategory)
  })
const CategoryStore = types.model({ category: types.optional(Category, {}) })
export default CategoryStore
///////////////////////////////////////////////////////////////
// Budget
const Budget = types
  .model('Budget', {
    totalIncome: 200,
    expenses: types.array(Category)
    // incomes: types.optional(types.array(Category), [])
  }).actions({
    addDummyData() {
      self.expenses.push(initialStateExpenses)
    }
})
const BudgetStore = types.model({ budget: types.optional(Budget, {}) })
export default BudgetStore


const initialStateExpenses = {
  id: '123',
  name: 'Food',
  subCategories: [
    {
      id: '1314',
      name: 'Grocery',
      amount: 250
    },
    {
      id: '1442',
      name: 'Restaurants',
      amount: 50
    }
  ]
}
javascript reactjs mobx mobx-state-tree
1个回答
0
投票

费用的类型为Category [],您正在传递一个对象。我假设您要从subCategories设置费用。如果是这样,您可以尝试此操作

    addDummyData() {
      initialStateExpenses.subCategories.forEach(ex => self.expenses.push(ex))
    }
or
    addDummyData() {
      self.expenses = initialStateExpenses.subCategories
    }

一种更好的方法是通过args将initialStateExpenses传递给addDummyData函数,因此您的模型不依赖于外部变量

    addDummyData(initialStateExpenses) {
      initialStateExpenses.subCategories.forEach(ex => self.expenses.push(ex))
    }
or
    addDummyData(initialStateExpenses) {
      self.expenses = initialStateExpenses.subCategories
    }

then use it like
    budget.addDummyData(initialStateExpenses)
© www.soinside.com 2019 - 2024. All rights reserved.