如何在 React Native 中显示所有接收到的坐标?

我想同时显示通过MQTT接收的所有坐标,但目前代码仅显示最新的纬度和经度对。有人有什么建议吗?


constructor(props) {

  super(props);

  this.state = {

    coordinates: [

      {latitude: 0, longitude: 0}

    ]

  };

};

componentDidMount() {

  client.on('connect', () => {

    client.subscribe('topic');

  });


  client.on('message', (_topic, message) => {

    var parsedBody = JSON.parse(message.toString());

    var mqttLat = parsedBody["latitude"];

    var mqttLong = parsedBody["longitude"];

    this.setState({

      coordinates: [

        {latitude: mqttLat, longitude: mqttLong}

      ]

    });

  });

};

<View>

  <MapView>

    {this.state.coordinates.map((marker, i) => (

      <Marker

        key = {i}

        coordinate = {{

          latitude: marker.latitude, 

          longitude: marker.longitude

        }}>

      </Marker>

    ))}

  </MapView>

</View>


慕的地6264312
浏览 132回答 1
1回答

斯蒂芬大帝

我想问题在于您在状态中保存坐标的方式。如果要保留比一个坐标更多的坐标,请将它们推送到坐标数组,而不是覆盖前一个坐标。&nbsp; client.on('connect', () => {&nbsp; &nbsp; client.subscribe('topic');&nbsp; });&nbsp; client.on('message', (_topic, message) => {&nbsp; &nbsp; var parsedBody = JSON.parse(message.toString());&nbsp; &nbsp; var mqttLat = parsedBody["latitude"];&nbsp; &nbsp; var mqttLong = parsedBody["longitude"];&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; coordinates: [&nbsp; &nbsp; &nbsp; &nbsp; ...this.state.coordinates,&nbsp; &nbsp; &nbsp; &nbsp; {latitude: mqttLat, longitude: mqttLong}&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; });&nbsp; });};```
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript