问题描述
我已经使用MobX和Redux大约6个月了.我发现对于大多数应用程序,我更喜欢MobX的简单性.但是,我喜欢Redux的单一商店概念.我听到其他人评论说他们用MobX创造了一个故事,我正在尝试确定最好的方法.目前,我创建了多个商店,然后将它们导入单个商店.
I have been using MobX and Redux for about 6 months. I have found that I prefer the simplicity of MobX for most applications. However, I like the single store concept of Redux. I have heard others comment that they create a single story with MobX and I am trying trying to determine the best way. Currently I create a multiple stores and then import them into a single store.
class UiStore {
@observable uiData;
constructor() {
this.uiData = {}
}
@action updateUI = (data) => {
this.uiData = {
data: data
};
}
}
let uiStore = new UiStore();
export default uiStore;
class Store {
@observable currentUser;
constructor() {
this.auth = authStore;
this.ui = uiStore;
}
}
let store = new store();
export default store;
在这里,我基本上创建了单个商店,然后将它们合并到单个商店中,类似于redux reducer的工作方式.
Here I basically create individual stores that are then combined into a single store similar to how a redux reducer works.
还有另一种/更好的方法吗?我曾考虑过可能将商店导入到不同的文件中,然后将某些方法和数据放在类的prototype
上.
Is there another / better way? I've thought about maybe import the a store in to different files and putting some methods and data on a class's prototype
.
推荐答案
我现在使用MobX已有一年多了,基本上可以这样做:
I use MobX for a year+ now and I basically do the same:
1)我有一个通常称为class Store {...}
1) I have one "master" or "parent" store usually named as class Store {...}
2)然后,我在主"商店中保留了一些较小的商店.
2) Then I have some smaller stores that are kept in "master" store.
3)我更喜欢在master的商店构造函数中构造子商店.此外,我发现有时我的子存储必须观察父存储的一些数据,因此我将this
传递给子构造函数:
3) I prefer to construct children stores within master's store constructor. Moreover, I found that sometimes my child store has to observe some data from parent store, so I pass this
into child constructors:
class UserStore {...}
class TodosStore {...}
class Store {
constructor() {
this.user = new UserStore(this);
this.todos = new TodosStore(this);
}
}
父母引用孩子,每个孩子引用父母.
Parent keeps references to children, and each child has reference to parent.
这篇关于为应用程序创建单个MobX存储的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!