【问题标题】:React Native Undefined is not an object - GeolocationReact Native Undefined 不是对象 - 地理位置
【发布时间】:2018-04-13 10:15:01
【问题描述】:

我使用的是 Windows 10 并且运行的是 Android 7.0 设备。

我正在尝试使用地理定位让设备显示其当前位置的经纬度 - 当用户按下按钮时。

我创建了一个按钮,并在用户单击它时显示了一条警告消息 - 到目前为止一切顺利。

然后我尝试添加获取当前位置,然后我的应用程序因错误而崩溃:

undefined 不是一个对象(评估 '_reactNative.Geolocation.getCurrentPosition')

这是我的代码:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Button,
  Alert,
  Geolocation
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>

        <Button
          onPress={() => {
            var loc = Geolocation.getCurrentPosition(geo_success, [geo_error], [geo_options]);
            Alert.alert(loc);

            //Alert.alert('You tapped the button!');
          }}
          title="Display GPS"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

“未定义不是对象”是什么意思,我该如何解决? (我之前尝试访问相机时遇到了同样的错误。)

【问题讨论】:

  • 将此添加到您的Manifest
  • @PritishVaidya 我的清单中已经有了。
  • 你在geo_success,error传递什么?
  • @PritishVaidya 可能没什么。我刚刚复制了我在以下位置找到的代码:facebook.github.io/react-native/docs/geolocation.html
  • 你需要传递一些方法给他们,现在变量是未定义的,查看一些教程以获得帮助

标签: react-native


【解决方案1】:

更新:该功能已从 react-native 核心中删除,因此以下答案不再无效。

React-Native (v 0.55) Geolocation 文档说,

作为浏览器 polyfill,此 API 可通过 navigator.geolocation global - 你不需要导入它。

不要从react-native 导入Geolocation。而是直接使用navigator.geolocation,它是一个全局对象。

例如,

navigator.geolocation.getCurrentPosition(
  (position) => console.log(position),
  (err) => console.log(err),
  { enableHighAccuracy: false, timeout: 8000, maximumAge: 10000 }
);

【讨论】:

    【解决方案2】:

    之前的答案不再准确。该库已从 react-native 核心移至其社区存储库。

    https://stackoverflow.com/a/56909007/4458849

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 2022-01-23
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多