如何将创建的React传单层发布到API?



我想在react-传单中绘制一个多边形,并将创建的图层发布到API。除此之外,还有不同的任务保持在数据状态。当前活动的任务在activeTask中保持。data和activeTask都是由上下文提供的。每次我发布一个图层,我都想添加当前活动任务的taskId。问题是:当我发布图层和taskId时,taskId是空的。因此,在第一个console.log(称为"activeTask 1")中,activeTask不是空的,所以一切正常。但是在第二个console.log(称为"activeTask 2")中,activeTask是空的。我怎么能访问activeTask张贴它的_id到一个API?

import React, { useContext } from 'react';
import axios from 'axios';
import { MapContainer, TileLayer, Marker, Popup, FeatureGroup, GeoJSON } from 'react-leaflet';
import { EditControl } from 'react-leaflet-draw';
import 'leaflet/dist/leaflet.css';
import 'leaflet-draw/dist/leaflet.draw.css';
import { DataContext } from './DataContext';

const LeafletComponent = () => {
const { dataContext, activeTaskContext } = useContext(DataContext);
const [activeTask, setActiveTask] = activeTaskContext;
const [data, setData] = dataContext;
const position = [51.505, -0.09]
let listAreas = [];
for (let i = 0; i < data.length; i++) {
if ("taskArea" in data[i]) {
for (let j = 0; j < data[i].taskArea.length; j++) {
if ("areaBoundaries" in data[i].taskArea[j]) {
listAreas.push(<GeoJSON key={data[i].taskArea[j]._id} data={JSON.parse(data[i].taskArea[j].areaBoundaries)} />);
}
}
}
}
console.log("activeTask 1");
console.log(activeTask);
const _onCreated = async (e) => {
console.log("activeTask 2");
console.log(activeTask);// <-- this activeTask is empty
const layer = e.layer;
const geoj = layer.toGeoJSON();
const postData = {
taskId: activeTask._id,// <-- this activeTask is empty
areaBoundaries: JSON.stringify(geoj)
}
try {
const response = await axios.post('http://localhost:3333/createarea', postData);
// do something with response
} catch (error) {
console.log(error);
}
};
return (
<MapContainer center={position} zoom={13} scrollWheelZoom={true}>
<FeatureGroup>
<EditControl position="topright" onCreated={_onCreated} draw={{
marker: false,
circle: false,
circlemarker: false,
rectangle: true,
polyline: false,
polygon: true
}} />
</FeatureGroup>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{listAreas}
</MapContainer>
)
}
export default LeafletComponent;

您是否尝试将_onCreated实现为依赖于activeTask的useCallback ?这样的

const _onCreated = React.useCallback(async (e) => {
//... 
}, [activeTask]);

反应→useCallback

你也可以考虑将for循环放入useMemo

const listAreas = React.useMemo(() => {
...
}, [data])

甚至可以使用ramdajs之类的东西来简化嵌套循环,就像这样

pipe(
map(x => x.taskArea),  
flatten,
filter(x => x && x.areaBoundaries)
map(x => (<GeoJSON key... />))
)(data)

相关内容

  • 没有找到相关文章

最新更新