React native和MobX:如何创建全局商店?

时间:2017-06-21 15:08:17

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

我目前正在尝试实现一个mobx存储,我可以随处调用它:

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

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

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

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

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

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

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};

1 个答案:

答案 0 :(得分:3)

您只需要一个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();