【问题标题】:React native and MobX: How to create a global store?React Native 和 MobX:如何创建全局商店?
【发布时间】:2017-11-24 13:56:41
【问题描述】:

我目前正在尝试实现一个 mobx 存储,我可以像这样从任何地方调用它:

import {userStore} from '../UserStore.js';

在文件末尾,我的导出功能如下所示:

const userStore = new UserStore();
export {userStore};

据我了解,每次调用 import 功能时,都会重新创建对象,其中导入 UserStore 的多个文件不共享相同的变量。

但是,我希望导入 UserStore 的每个文件都导入具有完全相同变量的相同对象。我怎样才能做到这一点?我不完全确定如何实现,因此任何想法和示例将不胜感激:)

完整的代码(对于 UserStore.js 声明),如果有帮助的话,如下(查看最底部的 export 语句)

import {observable, computed, action} from 'mobx';
import {ObservableMap, toJS} from 'mobx';
import {Fb} from './firebase.js';

class UserStore {

  /** GPS */
  @observable usrLng = 0.0;
  @observable usrLat = 0.0;
  @observable watchID = null;

  @action
  watchCurLocation() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      console.log("Recording GPS data from within the Store!!");
      this.usrLat = parseFloat(position.coords.latitude);
      this.usrLng = parseFloat(position.coords.longitude);
      }, (error) => console.log(JSON.stringify(error)), {
        enableHighAccuracy: true,
        timeout: 2000,
        maximumAge: 1000
      });
  }

  @action
  clearWatch() {
    navigator.geolocation.clearWatch(this.watchID);
  }
  /*/ GPS */

  /** BIKE BOOKING  */
  @observable interestBikeNo = -1;
  @observable bookedBikeNo = -1;

  @action
  setInterestBikeNo(bn) {
    this.interestBikeNo = bn;
  }

}

const userStore = new UserStore();
export {userStore};

【问题讨论】:

    标签: javascript reactjs react-native react-redux mobx


    【解决方案1】:

    您只需要一个 UserStore 类的单例实例

    示例演示

    let localInstance = null;
    
    export class Apple {
      static newInstance() {
        if (! localInstance)
          localInstance = new Apple();
        return localInstance;
      }
    }
    
    // usage
    
    import {Apple} from './apple';
    const instance = Apple. newInstance();
    

    在你的情况下,你可以使用一个简单的函数

    import {observable, computed, action} from 'mobx';
    import {ObservableMap, toJS} from 'mobx';
    import {Fb} from './firebase.js';
    
    class UserStore {
      // omitted
    }
    
    let userStore;
    export function getUserstore() {
      if (!userStore)
        userStore = new UserStore();
      return userStore;
    };
    

    代码中的某处

    // instead of 
    import {userStore} from './someUserStoreModule';
    
    // use 
    import {getUserstore} from './someUserStoreModule';
    const userStore = getUserstore();
    

    【讨论】:

    • 这是我很久以来见过的最优雅的解决方案,非常感谢!
    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2021-02-09
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多