gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:56:03 28 4
gpt4 key购买 nike

我有一个 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
}
}))

我想要的是将其拆分为两个文件,例如:
///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
}
}))

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

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

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

最佳答案

我们一直这样做。

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

// 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
}
})

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

// 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

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

// __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')
})

关于mobx-state-tree - 如何在多个文件中拆分 Mobx 状态树模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54080332/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com