如何从其他商店功能更新商店

时间:2017-05-18 11:18:35

标签: reactjs mobx mobx-react

我有2个商店,即AttachmentStore和CommentStore。

export class AttachmentStore {
  @observable attachments = []
}

export class CommentStore {
  @observable comments = []

  save_comment_and_attachment(comment, attachments) {
     this.comments.push(comment);
     //how can I push the attachment to the
     //attachments observable
  }

}

我知道我可以将附件声明为CommentStore observables的一部分,但是有什么方法可以更新CommentStore中可观察到的附件吗?

1 个答案:

答案 0 :(得分:1)

export class AttachmentStore {
  @observable attachments = [];

  @action add(attachments) {
    // ...
  }
}

export class CommentStore {
  @observable comments = [];
  attachmentStore = null;

  init(stores) {
    this.attachmentStore = stores.attachmentStore;
  }

  @action save_comment_and_attachment(comment, attachments) {
    this.comments.push(comment);
    this.attachmentStore.add(attachments);
  }
}

const stores = {
  attachmentStore: new AttachmentStore(),
  commentStore: new CommentStore(),
};
Object.values(stores)
  .filter(store => store.init)
  .forEach(store => store.init(stores));