使用react谷歌地图/api时,如何正确处理路线更改



我有一个react-router-dom路由器,其结构如下:

...
...
<BrowserRouter>
...
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/dashboard" component={MyAccount} />
<Route path="/register" component={Register} />
<Route path="/login" component={Login} />
</Switch>
</Router>
....

我的Landing组件使用@react-google-maps/api库有条件地显示MapContainer组件:

import { GoogleMap, LoadScript, Marker, InfoWindow } from '@react-google-maps/api';
const containerStyle = {
width: '100%',
height: '400px'
};
const MapComponent = ({ trips }) => { 
const [map, setMap] = useState(null);
const [ selected, setSelected ] = useState({});
const [ currentPosition, setCurrentPosition ] = useState({});
const success = position => {
const currentPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
setCurrentPosition(currentPosition);
};
const onSelect = item => {
setSelected(item);
};
const onLoad = useCallback(function callback(map) {
const bounds = new window.google.maps.LatLngBounds();
map.fitBounds(bounds);
setMap(map)
}, []);
const onUnmount = useCallback(function callback(map) {
setMap(null)
}, []);
const getPosition = () => {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
}
const setPositionFromGeolocation = async () => {
const res = await   getPosition();
const currentPosition = {
lat: res.coords.latitude,
lng: res.coords.longitude
}
setCurrentPosition(currentPosition);
}

useEffect(() => {
setPositionFromGeolocation(); 
},[setPositionFromGeolocation]);

return (
<LoadScript
googleMapsApiKey={process.env.REACT_APP_GOOGLE_MAPS_API_KEY}
>
<GoogleMap
mapContainerStyle={containerStyle}
center={currentPosition}
zoom={2}
onLoad={onLoad}
onUnmount={onUnmount}
>
{Array.from(trips).map(trip => {
const position = {
lng: trip.geometry.coordinates[0],
lat: trip.geometry.coordinates[1]
}
return (
<Marker 
key={trip._id}
position={position}
onClick={() => onSelect(trip)}
/>
)
})
}
{
selected.geometry && (
<InfoWindow
position={{
lng: selected.geometry.coordinates[0],
lat: selected.geometry.coordinates[1] 
}}
clickable={true}
onCloseClick={() => setSelected({})}
>
<p>{selected.description}</p>
</InfoWindow>
)
}

</GoogleMap>
</LoadScript>

);
}

当我更改路由时,我会在控制台中收到这些错误。我相信,之所以会出现这些错误,是因为我使用navigator.geolocation.getCurrentPosition来获得async/await语法的当前用户位置。除了我忘记添加的try/catch之外,有人能指出我遗漏了什么或做错了什么吗?

事实证明,我忘记将trips道具作为依赖项添加到useEffect,即从Landing组件传递到MapComponent组件。所以useEffect的最终版本应该是这样的:

useEffect(() => {
setPositionFromGeolocation(); 
},[trips]); 

最新更新