如何使用React在Arcgis JS地图组件中进行动态更改



我对Arcgis JS和React很陌生。正如这里所建议的,我正在使用一个带有useEffect钩子的功能组件来集成我的地图。

现在,当我点击列表的某一行时,我想在地图中显示一条线。单击时,我获取要显示的适当坐标,并将它们存储到上下文变量(dbPageContext.currentGeom(中。

问题是:当我想显示另一行时,整个映射组件必须重新渲染,因为我将行数组变量作为第二个参数传递给useEffect钩子。

const MapComp = () => {
const mapRef = useRef();
const dbPageContext = useContext(DbPageContext);

useEffect(() => {
const mainMap = new Map({
layers: [layer],
basemap: "arcgis-topographic", // Basemap layer service
});
const graphicsLayer = new GraphicsLayer();
mainMap.add(graphicsLayer);
const polyline = {
type: "polyline",
paths: dbPageContext.currentGeom, 
};
const simpleLineSymbol = {
type: "simple-line",
color: [0, 230, 250], 
width: 4,
};
const polylineGraphic = new Graphic({
geometry: polyline,
symbol: simpleLineSymbol,
});
graphicsLayer.add(polylineGraphic);
const view = new MapView({
container: mapRef.current,
map: mainMap,
spatialReference: {
wkid: 3857,
},
});
return () => {
view && view.destroy();
};
}, [dbPageContext.currentGeom]);
return (
<div>
<div className="webmap" ref={mapRef} />
</div>
);
};
export default MapComp;

如何在不更新整个地图组件的情况下仅更新图形层?如果有人能帮我找到解决方案,那就太好了。

EDIT:我还尝试在不使用useeffect钩子的情况下实现映射。但随后,什么也没显示。

您需要分离效果。在页面加载时,应该有一个创建映射的效果。然后第二个效果可以在dbPageContext.currentGeom改变时更新映射。

const MapComp = () => {
const mapRef = useRef();
const dbPageContext = useContext(DbPageContext);
// Memoize this, as you only need to create it once, but you also need
// it to be available within scope of both of the following useEffects
const graphicsLayer = React.useMemo(
() => new GraphicsLayer(), 
[]
);
// On mount, create the map, view, and teardown
useEffect(() => {
const mainMap = new Map({
layers: [layer],
basemap: "arcgis-topographic", // Basemap layer service
});
const view = new MapView({
container: mapRef.current,
map: mainMap,
spatialReference: {
wkid: 3857,
},
});
mainMap.add(graphicsLayer);
return () => {
view && view.destroy();
};
}, [])
// When dbPageContext.currentGeom changes, add a polyline
// to the graphics layer
useEffect(() => {
const polyline = {
type: "polyline",
paths: dbPageContext.currentGeom, 
};
const simpleLineSymbol = {
type: "simple-line",
color: [0, 230, 250], 
width: 4,
};
const polylineGraphic = new Graphic({
geometry: polyline,
symbol: simpleLineSymbol,
});

// Clear previously added lines (if that's what you want)
graphicsLayer.removeAll()
graphicsLayer.add(polylineGraphic);
}, [dbPageContext.currentGeom]);
return (
<div>
<div className="webmap" ref={mapRef} />
</div>
);
};
export default MapComp;

最新更新