为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地6264312 2022-08-18 10:39:19
我想同时显示通过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>
查看完整描述

1 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

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


  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}

      ]

    });

  });

};```


查看完整回答
反对 回复 2022-08-18
  • 1 回答
  • 0 关注
  • 61 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信