【问题标题】:Mobx model type for hashmaphashmap 的 Mobx 模型类型
【发布时间】:2021-07-08 13:11:42
【问题描述】:

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

  {
    "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), {}),
    })

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

【问题讨论】:

    标签: mobx mobx-react mobx-state-tree mobx-react-lite


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2014-01-09
      • 2018-10-06
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多