【发布时间】:2021-03-14 01:21:03
【问题描述】:
我正在尝试使用 GoogleMaps 设置边界,并且即使在进行错误检查时也收到“对象可能为空”错误。
背景是我试图在状态变化时将地图移动到我的标记并增加边界以显示所有标记。
其他相关文章(例如添加空检查)在修复此错误方面没有成效。
const [map, setMap] = React.useState(null)
const [loc, setLoc] = React.useState({lat: 0, lng: 0})
const [stores, setStores] = React.useState([])
const onLoad = React.useCallback(function callback(map) {
navigator.geolocation.getCurrentPosition((position) => {
console.log("Got position", position.coords);
setLoc({
lat: position.coords.latitude,
lng: position.coords.longitude
});
});
setMap(map)
}, [])
useEffect(() => {
if (stores && map !== null) {
const bounds = new window.google.maps.LatLngBounds();
stores.forEach(store => {
const latlng = new google.maps.LatLng(
//Get Lat
//Get Lon
);
bounds.extend(latlng)
});
map.fitBounds(bounds);
}
}, []);
...
return (
<LoadScript
googleMapsApiKey="AIzaSyDTd3ejyeGgdFBOZvaqwoa_7U2e2EJMc1w"
>
<Input/>
<GoogleMap
mapContainerStyle={containerStyle}
center={loc}
zoom={10}
onLoad={onLoad}
onUnmount={onUnmount}
>
...
每当状态发生变化时,我是否正确使用“useEffect”来更新地图上的边界?每当“商店”变量发生变化时,我都想更新地图的边界
【问题讨论】:
-
你可以使用optional chaining。
-
我会使用这样的可选链接吗:map?.fitBounds(bounds)
-
如果我尝试使用可选链,我会得到“从不”类型上不存在属性“fitBounds”。 map?.fitBounds(bounds)
标签: reactjs typescript react-google-maps