我有这两个事件onCreated和onDeleted,它们与地图中矩形的绘制有关。 除此之外,我还有一张表格,在其中列出了矩形的坐标。此列表的源/数据是listGeofences。
当我绘制一个新矩形时,我使用setListGeofences更新了listGeofences。这样做一切正常,它的表也会按预期更新。
问题来自onDeleted事件。例如,我绘制了三个矩形,并且在调试时观察const newState,它始终为空。 注意:newState开头已经为空。
预先感谢
const [listGeofences, setListGeofences] = useState([]);
const onCreated = useCallback((e: { layerType: any; layer: any; }) => {
var p1 = e.layer._latlngs[0][0];
var p2 = e.layer._latlngs[0][2];
let g: Geofence = new Geofence();
g.xMin = p1.lat;
g.yMax = p1.lng;
g.xMax = p2.lat;
g.yMin = p2.lng;
g.id = e.layer._leaflet_id;
const arr = [];
listGeofences.forEach(element => {
arr.push(element);
});
arr.push(g);
setListGeofences(arr as any);
}, [listGeofences]);
const onDeleted = useCallback((e: { layers: { eachLayer: (arg0: (layer: any) => void) => void; }; }) => {
const newState: Geofence[] = [...listGeofences];
e.layers.eachLayer((layer) => {
let index: number = newState.findIndex(x => x.id == layer._leaflet_id);
if (index != -1) {
newState.splice(index, 1);
}
});
setListGeofences(newState as any);
}, [listGeofences]);