首页 > 解决方案 > mobx -state-tree 中的代理

问题描述

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

当我在 useEffect 中打印 Budget.js 时,我对 Budget.js 进行了操作,这是 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
    }
  ]
}

标签: javascriptreactjsmobxmobx-state-tree

解决方案


费用是类别 [] 类型,您正在传递一个对象。我假设您想从subCategories. 如果是这样你可以试试这个

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

更好的方法是将initialStateExpensesvia args 传递给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)

推荐阅读