首页 > 解决方案 > 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), {}),
    })

但这不起作用。我不知道如何放置它,所以它有合适的钥匙。谢谢你的帮助

标签: mobxmobx-reactmobx-state-treemobx-react-lite

解决方案


对象文字非常适合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" }

推荐阅读