javascript - 如何在 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>
解决方案
我想问题在于您在该州保存坐标的方式。如果您想保留多个坐标而不是一个,请将它们推送到坐标数组而不是覆盖前一个。
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}
]
});
});
};```
推荐阅读
- java - 关闭执行器服务(等待终止时)和等待取消提交的任务(使用提交的期货)之间的比较
- arrays - Using a list to select the same position in multiple arrays in Python
- javascript - for-of 循环中的 Javascript 参考
- spring - 使用 Spring Boot 的远程 Tomcat 和 Vaadin
- javascript - 在 Javascript 中调用包含 promise 的递归函数
- c# - 只读修饰符对此项目无效
- angular-material - 每行最多 4 列 Angular Material 2 FlexLayout
- jenkins - 来自 Jenkins 的依赖检查报告未显示在 SonarQube 上
- angular - 如何同步执行异步代码Angular 5
- azure-devops - vsts 中的 Maven 测试自动化正在执行我的测试用例两次