reactjs - 警告失败的道具类型道具'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
。
解决方案
问题在于changePosition
使用属性简写设置状态时的方法,它将lat
和设置lon
为状态属性curLoc
而不是更新longitude
,latitude
因此curLoc
更新为:
curLoc: {lat: lat, lon: lon}
您可以根据目标属性使用相同的属性名称来修复它,如下所示:
changePosition(latitude, longitude){
console.log(latitude, longitude)
this.setState({curLoc: {latitude, longitude}});
console.log(this.state.curLoc)
}
快乐编码 退房
推荐阅读
- java - 库 Armen101 / AudioRecordView:不再出现块/条
- c++ - Clang 索引未检测到 C++20 ConceptDecls
- haxe - 有什么方法可以调用函数/引用以 haxe 中另一个变量的值命名的公共变量?
- php - Laravel PHP 不会在表单提交中显示所有图片/项目上传
- windows - 在 Windows 批处理文件中静音 For 的命令输出
- python - numpy 特征向量和特征值没有意义
- html - 将布局划分为 4 个元素,间距为 16px,使用 bootstrap 4 / responsive
- django - 如何最好地使用 git 管理数据库更新?
- reactjs - 如何使用分页处理 React Router 中的多个参数?
- c++ - 如何创建一个柯南包,包括对可以在所有平台上打包的仅标头库的测试