我在 React 中使用 useState 挂钩,并且在触发 onClick时geojson
不会更新状态。我认为 useEffect 正在覆盖函数中 onClick 更改的更新。为了更新状态,我在这里缺少什么?我使用 useEffect 的目的是让初始 goejson 加载。谢谢你的帮助。正在使用的 Mapbox 库:https ://uber.github.io/react-map-gl/#/<source data={geojson}>
_updateData
geojson
_updateData
{geojson}
const Map = () => {
const [viewport, setViewport] = useState({longitude: -98.58, latitude: 39.83, zoom: 3.5})
const [geojson, setGeojson] = useState(null)
useEffect(() => {
// GeoJSON
const locations = [];
let ref = fire.database().ref("...").orderByKey();
ref.once("value", snapshot => {
snapshot.forEach(function(childSnapshot) {
if (childSnapshot.val().Company !== "") {
locations.push(childSnapshot.val());
}
if (locations.length === 1219) {
var geojson = {
type: "FeatureCollection",
features: locations.map(item => {
return {
...
},
geometry: {
type: "Point",
coordinates: [item.Long, item.Lat]
}
};
})
};
setGeojson(geojson);
return geojson;
}
});
})
});
const _updateViewport = () => {
setViewport(viewport)
}
const _updateData = () => {
const locations = [];
let ref = fire.database().ref("...").orderByKey();
ref.once("value", snapshot => {
snapshot.forEach(function(childSnapshot) {
if (childSnapshot.val().Company !== "" && childSnapshot.val().Size === "Large") {
locations.push(childSnapshot.val());
}
if (locations.length === 232) {
var geojson = {
type: "FeatureCollection",
features: locations.map(item => {
return {
...
},
geometry: {
type: "Point",
coordinates: [item.Long, item.Lat]
}
};
})
};
console.log(geojson);
setGeojson(geojson);
return geojson;
}
});
})
}
return (
<ReactMapGL
{...viewport}
onViewportChange={_updateViewport}
width="100%"
height="100%"
mapStyle={mapStyle}
mapboxApiAccessToken={TOKEN}>
<Source type="geojson" data={geojson}>
<Layer {...icon} />
</Source>
<div style={navStyle}>
<NavigationControl onViewportChange={_updateViewport} />
<button style={navStyle} onClick={_updateData}>Update</button>
</div>
</ReactMapGL>
);
}
export default Map;