我正在尝试在地图上显示(车辆的)位置坐标以及每3秒获取的数据。每次获取数据(属性为“经度”和“纬度”的对象的数组)时,状态都会更新,我想更新地图上的“标记”以反映车辆的最新位置。
我知道我正在获取数据,但标记未显示。我的循环方式有问题吗?
class Mapbox extends Component {
constructor(props){
super(props)
this.state = {
active_vehicles: {},
};
}
componentDidMount() {
this.interval = setInterval(() => this.fetchData(), 3000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
fetchData = async () => {
let url = `${request_url}`
const response = await fetch(url, {
method: "GET",
headers: {
"Accept": "application/json",
}
});
const body = await response.json()
this.setState({ active_vehicles: body })
}
createMarkers = () => {
let markers = []
if(this.state.active_vehicles){
for (let i = 0; i < this.state.active_vehicles.length; i++) {
markers.push(
<Marker latitude={this.state.active_vehicles[i]["Latitude"]} longitude={this.state.active_vehicles[i]["Longitude"]}>
<div>x</div>
</Marker>
)
}
return markers
}
}
render() {
return (
<ReactMapGL
// mapbox API access token
mapboxApiAccessToken={MAPBOX_TOKEN}
mapStyle="mapbox://styles/mapbox/dark-v9"
{...this.state.viewport}
onViewportChange={(viewport) => this.setState({viewport})}>
<div>
{this.createMarkers()}
</div>
</ReactMapGL>
);
}
}
答案 0 :(得分:1)
this.active_vehicles
改成this.state.active_vehicles
(我发表评论后OP已更正)key
属性添加到for
循环内的标记组件中:<Maker key={i} ...