UNPKG

@pansy/react-mapbox-gl

Version:

🌍 基于 Mapbox GL 封装的 React 组件库

64 lines (63 loc) 1.93 kB
// src/components/StyleLoaded/index.tsx import { useRef, useEffect, useState } from "react"; import { isFunction } from "@rcuse/core"; import { useMap } from "../../hooks/useMap"; import { isStyleLoaded } from "../../utils/isStyleLoaded"; var StyleLoaded = (props) => { const { isFinishRender = false, children } = props; const { map } = useMap(); const [, setStyleLoaded] = useState(0); const themeStatus = useRef([0, 0, 0]); const checkStylePassRef = useRef(0); const forceUpdate = () => { setStyleLoaded((version) => version + 1); }; const checkStyle = () => { return ["031", "131"].includes(themeStatus.current.join("")); }; const handleStyleLoading = () => { themeStatus.current = [1, 0, 0]; forceUpdate(); }; const handleStyleData = () => { themeStatus.current[1] = themeStatus.current[1] + 1; if (themeStatus.current[1] === 3) { checkStylePassRef.current = checkStylePassRef.current + 1; } if (checkStyle()) { forceUpdate(); } }; const handleStyleLoad = () => { themeStatus.current[2] = 1; }; useEffect(() => { if (map) { if (isStyleLoaded(map)) { themeStatus.current = [0, 3, 1]; checkStylePassRef.current = 1; forceUpdate(); themeStatus.current = [0, 0, 0]; } map.on("styledataloading", handleStyleLoading); map.on("styledata", handleStyleData); map.on("style.load", handleStyleLoad); return () => { map.off("styledataloading", handleStyleLoading); map.off("styledata", handleStyleData); map.off("style.load", handleStyleLoad); }; } return void 0; }, [map]); if (isFunction(children)) { return children(checkStyle(), checkStylePassRef.current === 1); } if (!isFinishRender) { return checkStylePassRef.current > 0 && props.children; } return checkStyle() ? props.children : null; }; export { StyleLoaded };