在React Native中使用map函数

时间:2019-01-18 23:41:38

标签: javascript react-native react-native-maps

我试图在MapView上为状态数组中存储的每个位置绘制标记(称为标记),但是由于某些原因,当我尝试引用map函数内部的状态时,却无法定义。我检查了语法错误,但找不到问题。基本上,每次用户更改其位置时,我都希望将其标记设置为新位置。尝试在render()函数中使用map函数时发生错误。我在下面发布了错误的图片。

import React, {Component} from 'react';
import {AppRegistry,Text,View,StyleSheet} from 'react-native'
import Component1 from`enter code here` './Component1'
import Component3 from './Component3'
import Component4 from './Component4'
import MapView from 'react-native-maps'

export default class myapp extends Component{
  constructor(props){
    super();
    this.state ={
      markers: [
        {
          watchId: 0,
          latitude:3,
          longitude:2
        },
        {
          watchId: 2,
          latitude:3,
          longitude:2
        }
      ]

    }
  }

  componentDidMount(){
    navigator.geolocation.watchPosition((position)=>{
      var lat = parseFloat(position.coords.latitude)
      var long = parseFloat(position.coords.longitude)
      var id = parseFloat(position.coords.watchId)
      var found = false
      this.setState({markers: this.state.markers.map(marker =>{
        if(marker.watchId === id){
          found = true
          marker.latitude = lat
          marker.longitude = long
        }
      })});
    if(found === false){
      this.setState({markers:[{watchId:id,latitude:lat,longitude:long}]});
    }
    },null,{timeout:0,distanceFilter:0})
}
  render(){
    return(
      <View>
      <MapView style={{height:350,width:350,marginTop:300,alignSelf:'center'}}
      initialRegion={{
        latitude: 37.33,
        longitude: -121.4024,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      }}
      showsUserLocation={true}
      followsUserLocation={true}
      showsMyLocationButton={true}
      >
      {this.state.markers.map(marker =>{
        return(
                <MapView.Marker
                coordinate={{latitude:marker.latitude,longitude:marker.longitude}}
                title={"title"}
                description={"description ey"}

             />
        );
      })}

      </MapView>
      </View>

    );
  }
}
AppRegistry.registerComponent('myapp',()=>myapp);

The Error

1 个答案:

答案 0 :(得分:1)

您需要在componentDidMount中返回标记。

例如:

 this.setState({markers: this.state.markers.map(marker =>{
    if(marker.watchId === id){
      found = true
      marker.latitude = lat
      marker.longitude = long
    }
    return marker
  })});