【发布时间】:2020-04-19 18:26:19
【问题描述】:
我在 React 中使用了 useState 钩子,当 onClick 触发 _updateData 时,<source data={geojson}> 中的 geojson 状态不会更新。我认为 useEffect 正在覆盖更新的 geojson ,它改变了 _updateData 函数中的 onClick 。为了更新{geojson} 的状态,我在这里遗漏了什么?我使用 useEffect 的目的是让初始 goejson 加载。谢谢你的帮助。正在使用的 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;
【问题讨论】:
-
改变你的 useEffect ```useEffect(()=>{ //setGeojson },[geojsson]);
标签: reactjs mapbox-gl-js react-component react-state react-map-gl