循环状态并创建多个组件

Loop through state and create multiple components

我正在尝试在地图上显示(车辆的)位置坐标,其中包含我每 3 秒获取一次的数据。每次获取数据(具有属性 "Longitude" 和 "Latitude" 的对象数组)时,状态都会更新,我想更新地图上的 "markers" 以反映车辆的最新位置.

我知道我正在获取数据,但没有显示标记。我循环的方式有问题吗?

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>
    );
  }
}
  1. this.active_vehicles 更正为 this.state.active_vehicles(OP 在我发表评论后已更正)
  2. key属性添加到for循环内的Marker组件:<Maker key={i} ...