javascript - 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
}
]
}
解决方案
费用是类别 [] 类型,您正在传递一个对象。我假设您想从subCategories
. 如果是这样你可以试试这个
addDummyData() {
initialStateExpenses.subCategories.forEach(ex => self.expenses.push(ex))
}
or
addDummyData() {
self.expenses = initialStateExpenses.subCategories
}
更好的方法是将initialStateExpenses
via 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)
推荐阅读
- r - 将 R 更改为 UTC
- angular - 调用该模块时需要将一个模块中的值放入组件中
- python - 使用 pandas 创建特定的过滤器
- laravel - Laravel logoutOtherDevices 功能:登录后重定向到上次使用的 url 而不是 home url
- ruby - 找到正则表达式的实例,转换成整数,在同一个地方做数学和替换?
- mapbox - 使用地理编码 API 找不到 POI
- python - How to get date and time for Social networking sites emails using gmail-api?
- angular - 在 Angular 7 中添加没有额外变量的加载消息
- angularjs - 当用户将鼠标悬停在图标上时使光标成为手?
- android - Could not find manifest-merger.jar (com.android.tools.build:manifest-merger:26.0.1)