import MapView from "@arcgis/core/views/MapView";
useEffect(() => {
const map = new Map({
basemap: "arcgis-topographic", // Basemap layer service
});
const view = new MapView({
map: map,
center: [longitude, latitude], // Longitude, latitude
zoom: 11, // Zoom level
container: container.current, // Div element
popups: false, // Popups
});
}, []);
useEffect(() => {
//I need to use that MapView here
}, []);
我已经将view变量保存到state/ref中。但是没有成功。如何将MapView的实例作为全局变量访问
你好@Dostonbek,
正如我在上面的评论中解释的那样。你可以全局声明视图变量。或者,您可以使用ref
钩子使MapView
实例对两个useEffect
钩子都可用。此外,您可以使用useState
钩子作为墙。
import { useRef } from 'react';
import MapView from "@arcgis/core/views/MapView";
const mapViewRef = useRef();
useEffect(() => {
const map = new Map({
basemap: "arcgis-topographic", // Basemap layer service
});
mapViewRef.current = new MapView({
map: map,
center: [longitude, latitude], // Longitude, latitude
zoom: 11, // Zoom level
container: container.current, // Div element
popups: false, // Popups
});
}, []);
useEffect(() => {
const mapView = mapViewRef.current;
// Use the mapView instance here
}, []);
这可以通过使用react useState来完成。如果你在第一个useEffect中设置状态,你将能够访问你想要的所有功能。为了确保第二个useEffect能够访问视图,将view添加到第二个useEffect的依赖数组中,并确保状态已经设置好了。
import MapView from "@arcgis/core/views/MapView";
const [view, setView] = useState()
useEffect(() => {
const map = new Map({
basemap: "arcgis-topographic", // Basemap layer service
});
const view = new MapView({
map: map,
center: [longitude, latitude], // Longitude, latitude
zoom: 11, // Zoom level
container: container.current, // Div element
popups: false, // Popups
});
setView(view)
}, []);
useEffect(() => {
if(view){
// now you are able to use the view here
}
}, [view]);