我目前正在尝试实现Map-Component。我想将GPS逻辑移到另一个文件中。但是,我收到一个错误[_pGPS2.default.getCurLocation] is not a function

我的代码如下所示:

import { Provider as MobXProvider, observer } from 'mobx-react/native';
import { Store } from '../Store.js';

@observer
class pGPS {

  constructor(){
    this.gpsPos.lat = 0;
    this.gpsPos.lng = 0;

    this.watchID = null;
  }

  getCurLocation() {
    navigator.geolocation.getCurrentPosition((position) => {
      var lat = parseFloat(position.coords.latitude);
      var lng = parseFloat(position.coords.longitude);
      var initialRegion = {
        latitude: lat,
        longitude: lng
      };
      this.setState({
        gpsPosition: initialRegion
      });

    }, (error) => alert(JSON.stringify(error)), {
      enableHighAccuracy: true,
      timeout: 2000,
      maximumAge: 1000
    });
  }

    ...

}

export default new pGPS();


在下一个文件中,我调用如下函数:

import pGPS from './pGPS.js';
...
componentDidMount() {
    console.log("MapComponent did mount!");
    pGPS.getCurLocation();
    pGPS.watchCurLocation();
  }


如何正确导入可以调用的类的方法?我是JavaScript的初学者,欢迎任何想法! :)

最佳答案

这是一个instance类,而不是一个static类。您需要在调用其方法之前使用let gps = new pGPS()实例化它



class GPS {

  constructor() {
    this.lat = 0;
    this.lng = 0;
  }

  getCurLocation() {
    console.log(this.lat);
  }

}

let gps = new GPS();
gps.getCurLocation();

09-11 07:36