使用组件内部其他商店中的React Mobx操作和其他商店

时间:2020-10-27 02:57:19

标签: javascript reactjs native mobx

在我的react native应用程序中,我想使用mobx进行状态管理,我的商店分为多个商店/文件,并且由于我希望能够从其他商店调用商店动作,因此我正在实例化GlobalStore其他商店。

我希望能够通过组件执行类似的操作

import { PostStore }  from '../stores/PostStore.js'
import { UserStore }  from '../stores/UserStore.js'
import { VenueStore }  from '../stores/VenueStore.js'


class GlobalStore
{
    
    postStore = new PostStore(this);
    userStore = new UserStore(this);
    venueStore = new VenueStore(this);

}

export default new GlobalStore;

这样可以使我使用react-native Context-Provider API可以使用globalStore作为链接来调用我所有组件中的每个store操作:

在任何组件中我都可以做:

globalStore.postStore.listPosts()

但是我仍然不确定如何从OTHER STORES中访问其他商店操作。

如果我想在postStore内使用spinnerStore(显示未决,错误或成功状态的axios调用),怎么办?

@action.bound getPosts = flow(function * (payload) 
    {
        this.spinnerStore.setData({status: 1});
        try 
        {
            this.spinnerStore.setData({status: 2, response: response});
            let response = yield axios.get('/api/posts', { params: payload })
            return response;
        } 
        catch (error) {
            console.error(error);
            this.spinnerStore.setData({ status: 3, errors: error });
            throw error;
        }
    })

在这里spinnerStore将是不确定的...

1 个答案:

答案 0 :(得分:0)

但是我仍然不确定如何从OTHER STORES中访问其他商店操作。

实例化商店时,可以将其属性之一分配为另一个商店实例。这就是您包含在示例中的内容

class Foo {
  constructor(instance) {
    this.instance = instance
  }
}

class Bar {}

const foo = new Foo(new Bar());

foo.instance instanceof Bar; // true

现在您的foo实例可以访问在Bar上定义的任何公共属性/方法

class Foo {
  constructor(instance) {
    this.instance = instance
  }
}

class Bar {
  @observable isLoading = false;
  @observable data = null;

  @action
  getData() {
    this.isLoading = true;
    return axios.get('/foo').then((data) => {
      this.isLoading = false;
      this.data = data;
    }).catch(e => {
      this.isLoading = false;
    });
  }
}

const foo = new Foo(new Bar());

// in react
const MyComponent = ({ foo }) => (
  <div>
    {foo.instance.isLoading && <Spinner />}

    <button onClick={foo.instance.getData}>
     will call Bar action from Foo store
    </button>
  </div>
);

export default lodash.flowRight(
  mobx.inject((stores) => ({ foo: stores.fooStore })),
  mobx.observer
)(MyComponent)

在带有生成器的示例中,您不能使用粗箭头,因此this不再绑定到您的类实例,这就是为什么它将无法定义的原因。使用诺言和粗箭头解决了这个问题。