在useEffect内部,useState布尔值不会改变。请帮我。 我试图在 openlayers 地图中单击标记时弹出一个模式窗口。由于openlayers贴图是在useEffect内部执行的,所以marker点击事件也必须在useEffect内部,但是即使执行了setState,也出不出来一个boolean值。调试时确认boolean值发生了变化,但是取console.log时,该值没有变化,也没有出现模态窗口。请帮助我。
function App() {
const [mapObject, setMapObject] = useState({});
const [modalState, setModalState] = useState(false);
useEffect(() => {
const map = new OlMap({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: "map",
view: new View({
center: fromLonLat([126.752, 37.4713]),
zoom: 7,
minZoom: 3,
maxZoom: 17,
}),
});
jsondata.forEach((dataPoint) => {
const { lat, log } = dataPoint;
const coordinate = fromLonLat([lat, log]);
const markerFeature = new Feature({
geometry: new Point(coordinate),
});
const markerStyle = new Style({
});
const vectorLayer = new VectorLayer({
source: new VectorSource(),
});
markerFeature.setStyle(markerStyle);
vectorLayer.getSource().addFeature(markerFeature);
map.addLayer(vectorLayer);
// const handleMarkerClick = (event) => {
// setModalState(true);
// };
const handleMarkerClick = () => {
setModalState((modalState) => !modalState);
console.log("핸들러에서 모달 : " + modalState);
};
map.on("click", function (event) {
var feature = map.forEachFeatureAtPixel(
event.pixel,
function (feature) {
return feature;
}
);
if (feature === markerFeature) {
handleMarkerClick();
console.log("modalState : " + modalState);
}
});
});
setMapObject({ map });
return () => {
map.setTarget(null);
setMapObject(null);
};
}, []);
return (
<div>
{/* <Modal modalProps={modalState}>
</Modal> */}
{modalState && (
<ReactModal>
<button onClick={() => setModalState(false)}>닫기</button>
</ReactModal>
)}
</div>
);
}
我试图在 openlayers 地图中单击标记时弹出一个模式窗口。
function App() {
const modalStateRef = useRef()
const [modalState, setModalState] = useState(false);
modalStateRef.current = modalState;
useEffect(() => {
// ...
map.on("click", function (event) {
var feature = map.forEachFeatureAtPixel(
event.pixel,
function (feature) {
return feature;
}
);
if (feature === markerFeature) {
handleMarkerClick();
/* 👉 everywhere inside `useEffect`,
* replace `modalState` with `modalStateRef.current`
*/
console.log("modalState : " + modalStateRef.current);
}
});
}, [])
// ...
}
这是一个经典的 “React 过时闭包” 问题。您可以使用
useRef
钩子解决它。请参阅我的其他答案以更深入地解释为什么 useRef
有效
调试时,确认boolean值发生了变化,但是取console.log时,值没有变化
事实上,按照控制台记录的方式,如果您看到它没有更改,则意味着它已更改,因为该函数应该切换状态布尔值,所以您正在寻找相反的结果。参见这里
你提到过
我试图在 openlayers 地图中单击标记时弹出一个模式窗口。
你就这样做?
const handleMarkerClick = () => {
setModalState(true);
};
如果您希望模式打开,则实际上不必切换状态,而当您想隐藏它时,只需将其设置为
false
即可。