我正在使用自定义挂钩来调用 OpenRouteService API 并检索从 A 点到 B 点的最安全路线。我现在正在尝试在车辆之间切换(应该提供不同的路线),但车辆没有在 API 调用中更新即使参数已更新,如果我记录它。请参阅下面的代码和附加的屏幕截图。
为什么我的 API 调用没有接受更新的参数?
路由钩子.js
import { useState, useEffect } from 'react';
import Directions from '../apis/openRouteService';
import _ from 'lodash'
const useRoute = (initialCoordinates, avoidPolygons, vehicle) => {
const [route, setRoute] = useState({route: {}})
const [coordinates, setCoordinates] = useState(initialCoordinates);
const [routeLoading, setRouteLoading] = useState(true);
const [routeError, setRouteError] = useState(false);
useEffect(() => {
const fetchRoute = async () => {
setRouteError(false);
setRouteLoading(true);
try {
// Swap coordinates for openrouteservice
const copy = _.cloneDeep(coordinates)
let startLocation = copy[0];
let endLocation = copy[1];
console.log(vehicle);
// Logs 'cycling-regular' or 'driving-car'
// depending on the parameter when I call the hook
// Call openrouteservice api
const result = await Directions.calculate({
coordinates: [
[startLocation.latLng.lng, startLocation.latLng.lat],
[endLocation.latLng.lng, endLocation.latLng.lat],
],
profile: vehicle,
format: 'geojson',
avoid_polygons: avoidPolygons
})
console.log(result)
// When I check the result the query profile does not contain
// the updated parameter (see screencaps below).
setRoute(result);
} catch (error) {
setRouteError(true);
}
setRouteLoading(false);
}
fetchRoute();
}, [coordinates, avoidPolygons, vehicle]);
return [{ route, routeLoading, routeError }, setCoordinates];
}
export default useRoute;
给出一个完整的概述。在主要组件(VanillaMap.js)中,我有这些相关的片段:
const [vehicle, setVehicle] = useState('cycling-regular')
const [{ route, routeLoading, routeError }, setCoordinates] = useRoute([startLocation, endLocation], avoidPolygons, vehicle);
const updateVehicle = (state) => {
setVehicle(state);
}
<RouteInfo
route={route}
routeLoading={routeLoading}
routeError={routeError}
vehicle={vehicle}
updateVehicle={updateVehicle}
/>
然后我通过 RouteInfo.js 组件中的 updateVehicle 函数更新车辆。