在父元素中:
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传单渲染世界地图。我试图在拖放事件上更新可拖放标记的状态(位置对象)。
当dragend被触发时,updatePos也会被触发(就像它应该的那样)并调用props。updatePos .
问题是:在子进程的console.log中,我有标记的位置对象。这是期望的和正确的行为。在父组件中,正在调用updateNewPinPos函数,但是pos参数是一个空对象。即使我用标记调用函数,也会发生这种情况。_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}
/>