微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

hashmap 的 Mobx 模型类型

如何解决hashmap 的 Mobx 模型类型

我希望我的模型变量看起来像

  {
    "foo": {
      "viewed": false,"url": "https://www.google.com"
    },"bar": {
      "viewed": false,"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,baz: {
      viewed: false,url: "https://www.google.com"
    }
  }
});

console.log(exampleStore.devices.get("foo"));
// { viewed: false,url: "https://www.google.com" }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。