我有一个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]);