在父級中:
const [newPinPosition, setNewPinPosition] = React.useState({ lat: 0 , lng: 0 });
const updateNewPinPos = (pos) => {
console.log(pos);
setNewPinPosition({ lat: pos.lat, lng: pos.lng });
};
// in the render method of the parent react component
<Draggable
draggable={draggable}
newPinPosition={newPinPosition}
setCenterPos={() => { getCurrentCenter(map); }}
updatePos={() => { updateNewPinPos(newPinPosition); }}
/>
在孩子身上:
const updatePosition = useCallback(() => {
const marker = markerRef.current;
// console.log(`marker._latlng : ${marker._latlng}`);
props.updatePos(marker._latlng);
});
<StyledMarker
position={props.newPinPosition}
draggable={props.draggable}
ref={markerRef}
eventHandlers={{
dragend: () => {updatePosition();},
}}
>
我正在使用 React Leaflet 來渲染世界地圖。我正在嘗試在 dragend 事件上更新可拖動標記的狀態(位置物件)。
當 dragend 觸發時, updatePos 也會觸發(應該如此)并呼叫 props.updatePos (應該如此)。
問題是這樣的:在孩子的 console.log 中,我有標記的位置物件。這是預期的正確行為。在父組件中,正在呼叫 updateNewPinPos 函式,但 pos 引數是一個空物件。即使我使用 marker._latlang 物件呼叫函式,也會發生這種情況。為什么會這樣?這個物件是如何在孩子和父母之間“丟失”的?
我對反應很陌生,所以如果這是非常基本的,我很抱歉,但我在這方面遇到了很多困難。如有必要,我可以提供更多資訊。
uj5u.com熱心網友回復:
您沒有使用的依賴陣列useCallback
鉤子的useCallback第二個引數是它的依賴陣列,你應該把你在useCallback函式中使用的任何東西放在那里。只要依賴項相同,React 就會快取你的函式。
我建議不要useCallback在這種情況下使用。但如果你仍然想這樣做,你應該這樣做:
const updatePosition = useCallback(() => {
const marker = markerRef.current;
props.updatePos(marker._latlng);
}, [props.updatePos]);
同樣在您的父組件中,您應該使用給定的引數,或者按原樣傳遞函式,如下所示:
<Draggable
draggable={draggable}
newPinPosition={newPinPosition}
setCenterPos={() => { getCurrentCenter(map); }}
updatePos={updateNewPinPos}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483291.html
標籤:javascript 反应 反应钩子 传单 反应传单
上一篇:反應imgonError沒有觸發
