【问题标题】:Using react mobx actions from another stores inside components and other stores在组件和其他商店中使用来自其他商店的反应 mobx 动作
【发布时间】:2021-02-09 08:03:15
【问题描述】:

在我的 react 本机应用程序中,我想使用 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 作为链接调用我所有组件中的每个存储操作:

在我能做的任何组件中:

globalStore.postStore.listPosts()

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

如果在 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 将是未定义的...

【问题讨论】:

    标签: javascript reactjs native mobx


    【解决方案1】:

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

    当您实例化一个商店时,您可以将它的一个属性指定为另一个商店实例。这就是您在示例中包含的内容

    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 不再绑定到您的类实例,这就是它未定义的原因。使用 Promise 和粗箭头可以解决这个问题。

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-11-21
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多