首页 > 解决方案 > 在 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>
    )
  }
}

标签: react-nativereact-native-maps

解决方案


对象不是原始数据类型。因此,它们通过引用按值传递。在您的代码中,let reg = this.state.region您已经引用了 this.state.region。所以,当你改变 reg 时,你会直接改变 state,这是一个很大的反应。

我建议您使用扩展运算符制作新的状态副本。 let reg = { ...state, {} }


推荐阅读