ReactJS Mapbox-gl 类型无效:'container' 必须是字符串或 HTMLElement

ReactJS Mapbox-gl Invalid type: 'container' must be a String or HTMLElement

我正在使用 ReactJS 和 Mapbox GL JS 构建一个小应用程序。

const MapRender = () => {
  const mapContainerRef = useRef(null);
  const map = new mapboxgl.Map({
    container: mapContainerRef.current,
    style: "mapbox://styles/mapbox/streets-v11",
    center: [0, 0],
    zoom: 1
  });
  map();

  useEffect(()=>{
  ..........//Code 
  },[]);

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

export default MapRender;

我上面的代码基本上是在网页上显示地图。但我收到错误消息:

Invalid type: 'container' must be a String or HTMLElement.

如果我将 const map = new mapboxgl.Map() 放入 useEffect(),一切都会好起来的,但这意味着每次当我 setState 时,地图将再次调用并重新加载。

我希望在我的应用程序的整个运行期间使用同一张地图。

我该怎么做?

如果您不希望地图在每次有新数据传递给它时都重新初始化。您可以执行以下操作,当 ref 连接到容器时创建地图 div,如果已经创建,则不会创建地图。

export default function MapRender() {
  const ref = useRef(null);
  const [map, setMap] = useState(null);
  useEffect(() => {
    if (ref.current && !map) {
      const map = new mapboxgl.Map({
        container: ref.current,
        style: "mapbox://styles/mapbox/streets-v11",
        center: [0, 0],
        zoom: 1
      });
      setMap(map);
    }
  }, [ref, map]);
  return <div className="map-container" ref={ref} />;
}

使用以下格式删除 TS 错误:

const content = useRef<string | HTMLElement>(null);

Mapbox gl地图实例创建一次的代码:

Stackblitz:https://stackblitz.com/edit/react-xnetjp?devtoolsheight=33&file=src/App.js

这是 mapbox 中的 TS 错误-gl.d.ts(声明文件)表示容器必须是字符串或 HTML 元素。

截图:

学习References

谢谢!