我希望我的模型变量看起来像
{
"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" }