在父级中:
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 对象调用函数,也会发生这种情况。为什么会这样?这个对象是如何在孩子和父母之间“丢失”的?
我对反应很陌生,所以如果这是非常基本的,我很抱歉,但我在这方面遇到了很多困难。如有必要,我可以提供更多信息。
您没有使用的依赖数组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}
/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句