如何在多个文件中拆分 Mobx 状态树模型?

Ale*_*rls 4 mobx-state-tree

我有一个 Mobx 状态树模型已经长得太长了,我想将它拆分到多个 javascript 文件中。

下面是部分代码的演示:

///file1.js
 import { types } from "mobx-state-tree";

export const ExampleModel = types
.model("Example", {
    id: types.identifier,
    name: types.optional(types.string, ""),
    anotherName: types.optional(types.string, ""),

})
.views(self => ({
    get test() {
        return "test"
    }
}))
.views(self => ({
    get anotherTest() {
        return "anotherTest"
    }
}))
.actions(self => ({
    setName(name) {
        self.name = name
    }
}))
.actions(self => ({
    setAnotherName(name) {
        self.anotherName = name
    }
}))
Run Code Online (Sandbox Code Playgroud)

我想要的是将其拆分为两个文件,例如:

///file1.js
import { types } from "mobx-state-tree";

export const ExampleModel = types
.model("Example", {
    id: types.identifier,
    name: types.optional(types.string, ""),
    anotherName: types.optional(types.string, ""),

})
.views(self => ({
    get test() {
        return "test"
    }
})) 
.actions(self => ({
    setName(name) {
        self.name = name
    }
}))


///file2.js
import { ExampleModel } from "./file1.js";
ExampleModel.views(self => ({
    get anotherTest() {
        return "anotherTest"
    }
})).actions(self => ({
    setAnotherName(name) {
        self.anotherName = name
    }
}))
Run Code Online (Sandbox Code Playgroud)

您可以在此处看到我正在尝试将视图和操作移动到单独的 javascript 文件中。我希望我需要在这两个文件之间进行某种导入和导出,但我不知道该怎么做。

我知道 Mobx 状态树具有组合功能,如下所示:https ://nathanbirrell.me/notes/composition-mobx-state-tree/

但我想要一些比这更简单的东西......我不想设置多个模型,我只需要能够在多个 javascript 文件中传播模型。

Lui*_*anz 8

我们一直这样做。

只需分别导出您的操作和视图:

// file1.js
import { types } from "mobx-state-tree"

export const props = {
    id: types.identifier,
    name: types.optional(types.string, ""),
    anotherName: types.optional(types.string, ""),

}
export const views = self => ({
    get test() {
        return "test"
    }
})
export const actions = self => ({
    setName(name) {
        self.name = name
    }
})
Run Code Online (Sandbox Code Playgroud)

然后,从它们创建最终商店:

// store.js
import { types } from "mobx-state-tree"
import * as file1 from "./file1"
import * as file2 from "./file2"

const Store = types
  .model('Store')
  .props(file1.props)
  .views(file1.views)
  .actions(file1.actions)
  .props(file2.props)
  .views(file2.views)
  .actions(file2.actions)

export default Store
Run Code Online (Sandbox Code Playgroud)

您还可以创建自己的商店进行测试,仅从一个文件:

// __tests__/file1.js
import { types } from "mobx-state-tree"
import { actions, views, props } from "./file1"

const Store = types
  .model('Store')
  .props(props)
  .views(views)
  .actions(actions)
const store = Store.create(myTestSnapshot)

test('setName should set the name prop', () => {
  store.setName('john')
  expect(store.name).toBe('john')
})
Run Code Online (Sandbox Code Playgroud)