我目前正在尝试实现一个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};
最佳答案
您只需要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();