[英]API call with React custom hook not taking in updated parameter
我正在使用自定义挂钩来调用 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 function 更新车辆。
通过创建 Directions object 每次调用的新实例来解决:
const Directions = new openrouteservice.Directions({
api_key: "XXXXX"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.