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

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

问题描述

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

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.

如果我将 const map = new mapboxgl.Map()放入 useEffect()中,一切都会很好,但这是每次我 setState 时的意思>地图将再次调用并重新加载.

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.

我该怎么做?

推荐答案

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

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无效类型:“容器"必须为String或HTMLElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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