gpt4 book ai didi

ReactJS Mapbox-gl 无效类型 : 'container' must be a String or HTMLElement

转载 作者:行者123 更新时间:2023-12-04 03:39:42 38 4
gpt4 key购买 nike

我正在使用 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;

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

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

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

我希望在我的应用程序的整个运行期间使用相同的 map 。

我该怎么做?

最佳答案

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

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 无效类型 : 'container' must be a String or HTMLElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66271302/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com