首页 > 解决方案 > 如何在 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>

标签: javascriptreact-native

解决方案


我想问题在于您在该州保存坐标的方式。如果您想保留多个坐标而不是一个,请将它们推送到坐标数组而不是覆盖前一个。

  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: [
        ...this.state.coordinates,
        {latitude: mqttLat, longitude: mqttLong}
      ]
    });
  });
};```

推荐阅读