What is the best way to create a single MobX store for an app?

 ̄綄美尐妖づ 提交于 2019-12-03 07:33:54

问题


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;

Here I basically create individual stores that are then combined into a single store similar to how a redux reducer works.

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.


回答1:


I use MobX for a year+ now and I basically do the same:

1) I have one "master" or "parent" store usually named as class Store {...}

2) Then I have some smaller stores that are kept in "master" store.

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.



来源:https://stackoverflow.com/questions/43126615/what-is-the-best-way-to-create-a-single-mobx-store-for-an-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!