react-native - 在 react-native-maps 上更改区域坐标时出错
问题描述
我收到一个错误“您尝试使用一个对象上latitude
的值设置键,该xx.xxxxx
对象是不可变的,并且在我的应用程序启动时或当我尝试通过回调函数更改区域的坐标时已被冻结。
我的目标是能够从输入字段(如谷歌地图)更改区域位置。但是每当我更改坐标时,我都会收到此错误。我尝试使用新坐标重新渲染地图并且效果很好,但这会产生很多请求。
有没有办法在不重新渲染整个地图的情况下为该区域提供新坐标并显示它?
这是我的代码:
export default class Map extends Component{
constructor(){
super();
this.state = {
region: {
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
},
radius: 500
}
}
componentWillMount(){
}
regionChange = (region) =>{
let reg = this.state.region;
reg.latitude = region.latitude;
reg.longitude = region.longitude;
this.setState({region:reg});
}
changeRadius = (radius) => {
this.setState({radius});
console.log("RADIUS", this.state.radius);
}
render(){
return (
<View style={ styles.map }>
<MapView
provider={PROVIDER_GOOGLE}
style={ styles.map }
region={this.state.region}
onRegionChangeComplete={(region) => {this.regionChange(region)}}
onPress={(event) => this.regionChange(event.nativeEvent.coordinate)}
>
<MapView.Circle
center = { this.state.region }
radius = { this.state.radius }
strokeWidth = { 1 }
strokeColor = { '#1a66ff' }
fillColor = { 'rgba(230, 238, 255, 0.5)' }
onRegionChangeComplete = {(region) => {this.regionChange({region});console.log(region)}}
/>
<Marker
coordinate = { this.state.region }
title = {"Marker"}
description = {"Marker description"}
/>
</MapView>
<Slider
step={50}
maximumValue={2000}
onValueChange={(value) => this.changeRadius(value)}
value={this.state.radius}
style={{marginTop:10}}
/>
<Autocomplete regionChange={(reg) => this.regionChange(reg)} />
</View>
)
}
}
解决方案
对象不是原始数据类型。因此,它们通过引用按值传递。在您的代码中,let reg = this.state.region
您已经引用了 this.state.region。所以,当你改变 reg 时,你会直接改变 state,这是一个很大的反应。
我建议您使用扩展运算符制作新的状态副本。
let reg = { ...state, {} }
推荐阅读
- spring-boot - Springboot 禁用选定的普罗米修斯指标
- javascript - 从嵌套的 json 数组中删除属性
- javascript - jQuery向Node的每个孩子添加事件
- vb.net - 通过比较关系数据的最后记录状态值来检索数据
- c++ - 如何使用 VSCode 在 C++ 中观看中文字符串?
- asp.net - 为什么水晶报表总是显示在开发者端打开的第一个订单?
- python - 如何使用这个标记器来标记一串代码?
- sql - SQL 查询以查找特定月份中的最后一个事件
- bash - 在 shell 脚本中执行 sql loader 后如何捕获被拒绝的记录数?
- mongodb - 如何过滤 MongoDB 中计数大于一的数据?