【发布时间】:2021-05-21 01:02:00
【问题描述】:
我的 React Typescript 应用正在使用 react-leaflet 和 react-leaflet-markerclusterer 显示带有标记集群的传单地图。
但是,我无法让地图显示地图视图内的所有集群标记。我正在尝试 convert this JS solution 到 Typescript。
中显示的错误之一。 JS 控制台是
无法在回调中调用 React Hook “useMap”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用
在VSCode中,也存在Typescript错误
对象可能是'未定义'.ts(2532)
上线
const groupBounds = group.getBounds();
为什么会发生这种情况,编写此 Typescript 代码的正确方法是什么?
import React, { useEffect, useRef } from 'react';
import { MapContainer, TileLayer, Marker, useMap } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-markercluster';
interface IProps {
markers: {
lat: number;
lon: number;
}[];
mapCenter: {
lat: number;
lon: number;
};
}
export function MapView({markers, mapCenter}: IProps): JSX.Element {
const groupRef = useRef();
useEffect(() => {
if (groupRef !== undefined) {
const group = groupRef.current;
const map = useMap(); // ERROR: React Hook "useMap" cannot be called inside a callback.
const groupBounds = group.getBounds(); // ERROR: Object is possibly 'undefined'.ts(2532)
map.fitBounds(groupBounds);
}
}, []);
return (
<MapContainer
center={[mapCenter.lat, mapCenter.lon]}
zoom={10}
style={{ width:'100%', height:'100vh' }}
className='markercluster-map'
>
<TileLayer
url={`https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=${access_token}`}
/>
<MarkerClusterGroup ref={groupRef}>
{
markers.map((marker, index) => (
<Marker
position={[marker.lat, marker.lon]}
key={index}
/>
))
}
</MarkerClusterGroup>
</MapContainer>
)
}
【问题讨论】:
标签: javascript reactjs typescript leaflet react-leaflet