ReactJS Mapbox-gl 无效类型:“容器"必须是字符串或 HTMLElement [英] ReactJS Mapbox-gl Invalid type: 'container' must be a String or HTMLElement

查看:17
本文介绍了ReactJS Mapbox-gl 无效类型:“容器"必须是字符串或 HTMLElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

const MapRender = () =>{const mapContainerRef = useRef(null);const map = new mapboxgl.Map({容器:mapContainerRef.current,样式:mapbox://styles/mapbox/streets-v11",中心:[0, 0],缩放:1});地图();useEffect(()=>{..........//代码},[]);返回 (<div><div className="map-container";ref={mapContainerRef}/>

);};导出默认 MapRender;

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

无效类型:'container' 必须是字符串或 HTMLElement.

如果我把 const map = new mapboxgl.Map() 放到 useEffect() 中,一切都会好起来的,但是每次当我 setState> 地图将再次调用并重新加载.

我希望在我的应用程序的整个运行时使用相同的地图.

我该怎么做?

解决方案

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

导出默认函数 MapRender() {const ref = useRef(null);const [map, setMap] = useState(null);useEffect(() => {if (ref.current && !map) {const map = new mapboxgl.Map({容器:ref.current,样式:mapbox://styles/mapbox/streets-v11",中心:[0, 0],缩放:1});设置地图(地图);}}, [参考, 地图]);return 

;}

I'm building a small App using ReactJS and 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;

My code above basiclly display a map on a webpage. But I got the error messenge:

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

Everythings will be fine if I put const map = new mapboxgl.Map() into useEffect() but it's mean eachtime when I setState the Map will call and reload again.

I expect the use the same map during the whole runtime of my app.

How can I do that ?

解决方案

If you do not want the map to be reinitialized again every single time there is new data being passed to it. You can do the following where, the map is created when the ref is connected to the container div and it will not create the map if it's already been created.

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} />;
}

这篇关于ReactJS Mapbox-gl 无效类型:“容器"必须是字符串或 HTMLElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆