我想同时显示通过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}
]
});
});
};```
添加回答
举报
0/150
提交
取消