警告失败的道具类型当更新mapView时,道具'x'被标记为必需

时间:2019-03-08 13:21:46

标签: reactjs react-native expo

我在expo / react natives mapView上遇到一些问题,为mapView提供了一个初始位置,然后我试图为用户获取当前位置并更新地图。 我目前拥有的是:

import React, {Component} from 'react';
import { StyleSheet, View } from 'react-native';
import {MapView, Permissions, Location} from 'expo';

export default class MapScreen extends Component {
constructor(props) {
    super(props);
    this.state = {
        curLoc: { latitude: 42.229138, longitude: -122.081949 },
        curAng: 45,
        latitudeDelta: 0.922, 
        longitudeDelta: 0.0421,
    };
    this.changePosition = this.changePosition.bind(this);

}
changePosition(lat, lon){
    console.log(lat, lon)
    this.setState({curLoc: {lat, lon}});
    console.log(this.state.curLoc)
}

componentDidMount() {
    this._getLocationAsync();
}
_getLocationAsync = async () => {
    console.log("get location async hit")
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
        console.log("Permission denied")



    }
    let location = await Location.getCurrentPositionAsync({});
    console.log(location.coords)
    tempLat = location.coords.latitude;
    temLon  = location.coords.longitude;
    console.log(this.state.curLoc)
    this.changePosition(tempLat,temLon);

}

render(){
    return(
        <MapView style={styles.fullMap}
         initialRegion={{
             latitude: this.state.curLoc.latitude,
             longitude: this.state.curLoc.longitude,
             //spread the attributes from curLoc
             latitudeDelta: this.state.latitudeDelta,
             longitudeDelta: this.state.longitudeDelta,

         }}
        />

    )
}
}
const styles = StyleSheet.create({
fullMap: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: '100%',
    width: '100%'


}
})

我收到的控制台错误是:警告:道具类型失败:道具initialRegion.latitudeMapView中标记为必需,但其值为undefined

1 个答案:

答案 0 :(得分:1)

问题是在使用属性速记设置状态的changePosition方法中,该方法将latlon设置为curLoc的状态属性,而不更新longitudelatitude由于curLoc被更新为:

curLoc: {lat: lat, lon: lon}

您可以通过根据目标属性使用相同的属性名称来修复它,如下所示:

changePosition(latitude, longitude){
    console.log(latitude, longitude)
    this.setState({curLoc: {latitude, longitude}});
    console.log(this.state.curLoc)
}

快乐编码Check out