我目前正在使用mobx并做出本机反应,我已经在下面创建了用户可以获取其地理位置的文件。我的问题是:
我怎样才能做类似的事情 -
{this.props.store.geo?检索到的地理位置:null}
提前致谢
LocationStore.js:
import { observable, action, computed } from 'mobx'
class LocationStore{
@observable geo = [];
@action fetchLocation() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude, position.coords.longitude);
this.geo = {
lat: position.coords.latitude
}
console.log(this.geo);
},
(error) => this.error= {error},
{ enableHighAccuracy: false, timeout: 20000 },
);
}
}
export default new LocationStore()
LocationScreen.js
答案 0 :(得分:0)
这里明确的关注点是你没有承诺使用@action!我建议放弃@action和@computed,然后选择无状态解决方案:
LocationStore.js:
import {observable} from 'mobx'
class LocationStore {
@observable geo = {};
@observable error = {};
@observable isLoading = false;
async fetchLocation() {
this.isLoading = true;
try {
await navigator.geolocation.getCurrentPosition((position) => {
this.geo = {
lat: position.coords.latitude
}
this.isLoading = false;
}
);
} catch (e) {
this.error = e
this.isLoading = false;
}
}
}
export default new LocationStore()
component.js
async fetchLocation(){
await this.props.LocationStore.fetchLocation();
}
render () {
const { geo, error, isLoading } = this.props.LocationStore
return (<View>
<Button onPress={this.fetchLocation.bind(this)}></Button>
{(!!isLoading)?<Text>{geo}</Text>:<Text>Loading</Text>}
</View>)
}
退房&#39; async / await&#39;欲获得更多信息: https://mobx.js.org/best/actions.html