What is the best way to create a single MobX store

2020-05-20 01:41发布

问题:

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.