mobx - hashmap 的 Mobx 模型类型
问题描述
我希望我的模型变量看起来像
{
"foo": {
"viewed": false,
"url": "https://www.google.com"
},
"bar": {
"viewed": false,
"url": "https://www.google.com"
},
"baz": {
"viewed": false,
"url": "https://www.google.com"
}
}
我有一个像这样的单独模型
import { types as t } from "mobx-state-tree"
export const deviceInstruction = t.model({
viewed: t.boolean,
url: t.string
})
type DeviceInstructionType = typeof deviceInstruction.Type
export interface IDeviceInstruction extends DeviceInstructionType {}
并希望像
export const exampleStore = t
.model({
devices: t.optional(deviceInstruction), {}),
})
但这不起作用。我不知道如何放置它,所以它有合适的钥匙。谢谢你的帮助
解决方案
对象文字非常适合map
:
import { types as t } from "mobx-state-tree";
const DeviceInstruction = t.model({
viewed: t.boolean,
url: t.string
});
const ExampleStore = t.model({
devices: t.map(DeviceInstruction)
});
const exampleStore = ExampleStore.create({
devices: {
foo: {
viewed: false,
url: "https://www.google.com"
},
bar: {
viewed: false,
url: "https://www.google.com"
},
baz: {
viewed: false,
url: "https://www.google.com"
}
}
});
console.log(exampleStore.devices.get("foo"));
// { viewed: false, url: "https://www.google.com" }
推荐阅读
- html - 创建具有自定义列大小的html表
- ios - 如何将数据从一个模型传递到另一个模型?
- javascript - 使用类为元素应用样式的 withStyles 错误
- python - 多进程环境中的 cx_Oracle python delete 语句
- python - 从三个文本中计算单词
- reactjs - find 仅返回日期的第一个数据
- java - springboot中的调度器,用于spring批处理的大数据交替
- algorithm - 您如何计算具有多个来源的 Djikstra 热图?
- swift - 如果集合视图位于 UIScrollView 中,是否会重用 UICollectionViewCell?
- angular - Angular:当列表中没有数据时如何显示消息?