Leaflet in React.js - "dragend" event exception: "TypeError: Cannot read property 'call' of undefined"

Leaflet in React.js - "dragend" event exception: "TypeError: Cannot read property 'call' of undefined"

当此事件发生时,即当用户完成拖动标记时,我得到此异常。这是我的 React 组件:

import {useState, useEffect, useContext} from 'react';
import L from 'leaflet';
import styles from './styles.module.scss';
import { MapContext } from './../../../../context/MapProvider';

const ZonesBar2 = () => {
    const [definingZone, setDefiningZone] = useState(false);
    const [markerInput, setMarkerInput] = useState({lat: '', lng: ''});
    // const [] = useState();
    const [markers, setMarkers] = useState([]);
    const {contextData, setContextData} = useContext(MapContext);
    const {mapRef, clickLocation} = contextData;

    useEffect(()=>{
        if(clickLocation.lat) {
            // Add markert to map
            let newMarker = L.marker([clickLocation.lat, clickLocation.lng], {draggable: true})
                .on('dragend', console.log('Marker dragged'))
                .addTo(mapRef);

            // Add to list of markers
            setMarkers((m)=>([...m, newMarker]));

            console.log(newMarker.getLatLng());
        }
    }, [clickLocation])

    return (
        <div className={styles.zonesbar}>
            <button onClick={()=>{setDefiningZone((p)=>(!p))}}>Nueva Zona</button>
            <div className={`${styles.newMarkerPanel} ${definingZone && styles.visible}`}>
                
                <label>
                    <span>Nombre:</span>
                    <input type="text" />
                </label>
                <label>
                    <span>Latitud:</span>
                    <input type="text" id='lat' />
                </label>
                <label>
                    <span>Longitud:</span>
                    <input type="text" />
                </label>
                <button>+ Marcador</button>

            </div>
        </div>
    )
}

export default ZonesBar2;

老实说,我不知道发生了什么......我确实需要你的专家的帮助。 这是错误的屏幕截图:

您必须传递函数引用:

 let newMarker = L.marker([clickLocation.lat, clickLocation.lng], {draggable: true})
                .on('dragend', console.log('Marker dragged'))
                .addTo(mapRef);

最后还要处理处理程序:

return ()=> { newMarker.off('dragend'); }

那里发生了很多事情,但我看到的是:

let newMarker = L.marker([clickLocation.lat, clickLocation.lng], {draggable: true})
  .on('dragend', console.log('Marker dragged')) // <-- bad times right here
  .addTo(mapRef);

当您写 console.log('something') 时,该表达式会立即被计算。并且 console.log returns undefined...所以 leaflet 试图触发一个 undefined 的函数。你需要这个:

let newMarker = L.marker([clickLocation.lat, clickLocation.lng], {draggable: true})
  .on('dragend', () => { console.log('Marker dragged') }) // <-- callback
  .addTo(mapRef);

现在您正在传递一个适当的回调,它是一个函数,而不是 console.log() 的 return 值。