首页 > 解决方案 > 警告失败的道具类型道具'x'在更新mapView时被标记为必需

问题描述

我在使用 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.latitude在 中标记为必需MapView,但其值为undefined

标签: reactjsreact-nativeexpo

解决方案


问题在于changePosition使用属性简写设置状态时的方法,它将lat和设置lon为状态属性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)
}

快乐编码 退房


推荐阅读