最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I inject a Store to another Store in mobX - Stack Overflow

programmeradmin0浏览0评论

I am using mobX in bination with React and Meteor and I need to be able to use information saved in one Store in another. Specifically, I need to have a reference of Store A in Store B in order to call an action of Store A and get the information that it had retrieved by subscribing to a collection. I used the @inject decorator but do not know how to call the action. Thank you

I am using mobX in bination with React and Meteor and I need to be able to use information saved in one Store in another. Specifically, I need to have a reference of Store A in Store B in order to call an action of Store A and get the information that it had retrieved by subscribing to a collection. I used the @inject decorator but do not know how to call the action. Thank you

Share Improve this question edited Sep 17, 2018 at 21:36 Tina Raissi asked Jun 29, 2017 at 6:02 Tina RaissiTina Raissi 411 silver badge5 bronze badges 1
  • 2 [Update:] I found out an efficient solution from point of view of the general architecture: it is better to have a root store which makes the access of different stores to the data possible. The necessity of different ponents of an application of having access to the same data is very mon, in order to avoid redundancy, it is possible to split the architecture on two levels. – Tina Raissi Commented Sep 17, 2018 at 21:40
Add a ment  | 

2 Answers 2

Reset to default 7

@inject is used to inject something from the Provider into a React ponent, not between stores.

You could just import the first store into the second store and call the action straight away.

Example

// store1.js
import { observable, action } from 'mobx';

class Store1 {
  @observable count = 0;

  @action increment() {
    ++this.count;
  }
}

export default new Store1();

// store2.js
import { observable, action } from 'mobx';
import store1 from './store1';

class Store2 {
  @observable name = 'foobar';

  constructor() {
    store1.increment();
  }

  @action changeName(name) {
    this.name = name;
  }
}

export default new Store2();

you can do it via following steps

// store1.js
import { observable, action } from 'mobx';

class Store1 {
  @observable count = 0;

  @action increment() {
    ++this.count;
  }
}

export default new Store1();

// store2.js
import { observable, action } from 'mobx';
import store1 from './store1';
const store = new store1()

class Store2 {
  @observable name = 'foobar';

  @action changeName(name) {
    this.name = name;
  }

@action
increment(){
 store.increment();
}
}

export default new Store2();
发布评论

评论列表(0)

  1. 暂无评论