我在React中使用useState挂钩,当geojson
触发onClick时,<source data={geojson}>
的状态不会在_updateData
中更新。我要更改onClick的更新后的geojson
可以正确地在_updateData
中使用console.log,但是data={geojson}
不会更新和重新呈现。为了更新{geojson}
的状态,我在这里缺少什么?谢谢你的帮助。正在使用的Mapbox库:https://uber.github.io/react-map-gl/#/
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;
答案 0 :(得分:0)
我建议您改用 useReducer 钩子,因为 useState 在让您知道更新时有点问题,我不知道为什么?!
答案 1 :(得分:0)
如果只想首次加载,请使用如下所示的useEffect:
useEffect(function,[dependency] or [])