问题
I am currently trying to implement a mobx storage which I can call from everywhere like so:
import {userStore} from '../UserStore.js';
At the end of the file, my export functionality looks as follows:
const userStore = new UserStore();
export {userStore};
As I understand, everytime I call the import
functionality, the object gets re-created with which multiple files that import UserStore don't share the same variables.
However, I want that every file that imports UserStore
imports the same object with the exact same variables. How can I achieve this? I am not fully sure how to achieve, so any ideas and examples would be appreciated :)
The full code (for the UserStore.js declaration), if of any help, is as follows (look at the very bottom for the export statement)
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:
You simply need a singleton instance of UserStore
class
Sample demo
let localInstance = null;
export class Apple {
static newInstance() {
if (! localInstance)
localInstance = new Apple();
return localInstance;
}
}
// usage
import {Apple} from './apple';
const instance = Apple. newInstance();
In your case, you can use a simple function
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;
};
Somewhere in code
// instead of
import {userStore} from './someUserStoreModule';
// use
import {getUserstore} from './someUserStoreModule';
const userStore = getUserstore();
来源:https://stackoverflow.com/questions/44679881/react-native-and-mobx-how-to-create-a-global-store