为什么此OpenLayersMap不会显示在ReactJS应用程序中?

cotxawn7  于 2023-02-18  发布在  React
关注(0)|答案(2)|浏览(125)

下面是我的OpenLayers组件的代码:

import React, { useState, useEffect, useRef } from 'react';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

function OpenLayer(props) {
    const [map, setMap] = useState();
    const mapElement = useRef();
    const mapRef = useRef();
    mapRef.current = map;

    useEffect(() => {
        const initialMap = new Map({
            target: 'map',
            layers: [
                new TileLayer({
                    source: new OSM(),
                }),
            ],
            view: new View({
                center: [0, 0],
                zoom: 0,
            }),
        });
        setMap(initialMap);
    }, []);

    return (
        <div>
            <div ref={mapElement} className="map-container" />
        </div>
    );
}

export default OpenLayer;

我在我的主应用程序中这样渲染它:

<Row className="mapRow">
        <OpenLayer />
    </Row>

我似乎不能得到任何东西返回...哦,这是我的css太:

.mapRow{
    text-align: center;
    height: 100%;
    width: 100%;
}

.map-container{
    height: 100vh;
    width: 100%;
  }

是不是有什么明显的东西我忽略了?

xytpbqjk

xytpbqjk1#

好吧,你只是用错误的方式初始化它,你仍然在map类中初始化map,但是你需要用你当前的map ref来初始化它,所以你需要在初始化阶段使用mapElement而不是map
所以应该是这样的:

const initialMap = new Map({
  target: mapElement.current,
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  view: new View({
    center: [0, 0],
    zoom: 0,
  }),
});

工作演示:

lsmd5eda

lsmd5eda2#

在useEffect结束时,你应该添加的另一个东西是return () => initialMap.setTarget(null),这将在Map组件卸载时释放Map资源。

相关问题