无法解构'reactLeaflet'的属性'MapContainer',因为它为 null



我有一个React功能组件,它在服务器端呈现了一个React传单映射。映射显示得很好,但当我添加一个点击事件处理程序函数传递给父组件时,我会收到错误:无法销毁"reactLeaflet"的属性"MapContainer",因为它为null这是子组件中的代码:

const MyMap = (props, ref) => {

const [ reactLeaflet, setReactLeaflet ] = useState(null);
const [ position, setPosition ] = useState(null);
useEffect(() => {
const loadData = async () => {
// react-leaflet errors if imported server-side (with "ReferenceError: window is not defined")
// not sure if this load can happen in parallel with leaflet.js or not
import('react-leaflet')
.then(leaflet => setReactLeaflet(leaflet))
.catch(error => noticeError(null, levels.error, error, "react-leaflet failed to load"));
};
loadData();
}, []);

const {
MapContainer,
Marker,
Popup,
TileLayer,
useMapEvents,
} = reactLeaflet;
const HandleClickMap = (e) =>{
const currMap = useMapEvents({ 
click() {
currMap.locate();
},
locationfound(e) {
setPosition(e.latlng);
currMap.flyTo(e.latlng, currMap.getZoom());
},
});
return position === null ? null : ( <Marker position={position}></Marker> );

};
useImperativeHandle(ref, () => ({
HandleClickMap,
}));

if (!reactLeaflet) {
return <LeafletCss />;
}

return <>
<LeafletCss />
<MapContainer
center={{ lat: 0, lng: 0 }}
zoom={13}
ref={ref}
scrollWheelZoom={false}
className={style.mapContainer}
>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
/>
<HandleClickMap />
</MapContainer>
</>;
};
export default forwardRef(MyMap);

当我添加useImperativeHandle钩子时,出现了这个问题。对原因的任何见解都将不胜感激。

在尝试访问其组件之前,检查reactLeaflet对象是否已导入

const MyMap = (props) => {
const {
MapContainer,
Marker,
Popup,
TileLayer,
useMapEvents,
} = props.reactLeaflet;
const [ position, setPosition ] = useState(null);
const HandleClickMap = (e) =>{
const currMap = useMapEvents({ 
click() {
currMap.locate();
},
locationfound(e) {
setPosition(e.latlng);
currMap.flyTo(e.latlng, currMap.getZoom());
},
});
return position === null ? null : ( <Marker position={position}></Marker> );

};
useImperativeHandle(props.ref, () => ({
HandleClickMap,
}));
return <>
<LeafletCss />
<MapContainer
center={{ lat: 0, lng: 0 }}
zoom={13}
ref={ref}
scrollWheelZoom={false}
className={style.mapContainer}
>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
/>
<HandleClickMap />
</MapContainer>
</>;
}
const MapLoader = (props, ref) => {

const [ reactLeaflet, setReactLeaflet ] = useState(null);
useEffect(() => {
const loadData = async () => {
import('react-leaflet')
.then(leaflet => setReactLeaflet(leaflet))
.catch(error => noticeError(null, levels.error, error, "react-leaflet failed to load"));
};
loadData();
}, []);
return (reactLeaflet ? 
<MyMap reactLeaflet={reactLeaflet} ref={ref} /> : 
<LeafletCss /> 
);
};
export default forwardRef(MapLoader);

相关内容

最新更新