开发者问题收集

React Native,TypeError:undefined 不是一个对象当它

2018-03-30
10149

React Native 说 Undefined 不是对象,但它显然是一个对象!!我不知道发生了什么。

查看以下代码。浏览到 render() 函数。请参阅以下内容... console.log(cords.coords);

console.log(cords.coords); 输出以下内容...

08:37:22: Object {
08:37:22:   "coords": Object {
08:37:22:     "accuracy": 5,
08:37:22:     "altitude": 0,
08:37:22:     "altitudeAccuracy": -1,
08:37:22:     "heading": -1,
08:37:22:     "latitude": 39.946313,
08:37:22:     "longitude": -82.810829,
08:37:22:     "speed": -1,
08:37:22:   },
08:37:22:   "timestamp": 1522413346644.865,
08:37:22: }

有人会说要检索此数据,您必须执行以下操作。 console.log(cords.coords.coords.latitude) 以获取纬度。但它说它未定义。即使我执行 console.log(cords.coords.coords) ,它仍然说它未定义?我做错了什么?

请注意 console.log(cords.coords); 是脚本中触发错误的地方

请记住,以下代码确实有效。仅当我将 console.log(cords.coords); 更改为 console.log(cords.coords.coords.latitude); 时,它才会中断

import React, { Component } from 'react';
import {Platform, StyleSheet, Dimensions, Text, View } from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
import { Constants, Location, Permissions } from 'expo';

export default class MapScreen extends Component<Props> {
 constructor(props) {
    super(props);
    this.state = {
      markers: [{
        title: 'hello',
        coordinates: {
          latitude: 39.946313,
          longitude: -82.810829
        },
      },
      {
        title: 'hello',
        coordinates: {
          latitude: 39.945838,
          longitude: -82.813018
        },  
      }
     ]
    }
    console.log("Get Geo Synce");
    this._getLocationAsync();
  }

  _getLocationAsync = async () => {
    console.log("load geo sync");
    //Location.setApiKey("AIzaSyBY45685CkDPy5a4ss29IL2ZjIvTvYTMyk");
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        locationResult: 'Permission to access location was denied',
      });
    }
    console.log("Loading Location 1");
    let location = await Expo.Location.getCurrentPositionAsync({ enableHighAccuracy: true });
    console.log("Retrieved Location");
    this.setState({ coords: location });
  };
  
  render() {
    const { params } = this.props.navigation.state;
    let coords = params ? params.coords.coords : null;
    let cords = this.state;
    console.log(cords.coords);
    //let coords = state.locationResult.coords;
    return (
          <View style={{flex: 1}}>
            <MapView
                style={ styles.container }
                initialRegion={{
                    latitude:coords.latitude,
                    longitude:coords.longitude,
                    latitudeDelta:0.0992,
                    longitudeDelta:0.0421,
                }}
            >
              {this.state.markers.map(marker => (
                <MapView.Marker 
                  coordinate={marker.coordinates}
                  title={marker.title}
                />
              ))}
            </MapView>
          </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
      width:'100%',
      height:'100%',
  },
});
1个回答

最好在组件在 componentDidMount 生命周期方法中挂载后发出 API 请求,而您的代码存在问题,在初始渲染时 this.state.coords 未定义,而一旦 API 请求得到解决,this.state 就会使用 this.setState 方法更新,并且 this.state.coords 已定义。因此,要使其正常工作,请尝试以下方法,

 return this.state.coords instanceof Object ? (
      <View style={{flex: 1}}>
        <MapView
            style={ styles.container }
            initialRegion={{
                latitude:coords.latitude,
                longitude:coords.longitude,
                latitudeDelta:0.0992,
                longitudeDelta:0.0421,
            }}
        >
          {this.state.markers.map(marker => (
            <MapView.Marker 
              coordinate={marker.coordinates}
              title={marker.title}
            />
          ))}
        </MapView>
      </View>
) : <Text>Fetching, Please wait....</Text>;
Raj Kumar N
2018-03-30