API 使用 React 自定义挂钩调用不接受更新的参数

API call with React custom hook not taking in updated parameter

我正在使用自定义挂钩来调用 OpenRouteService API 并检索从 A 点到 B 点的最安全路线。我现在正在尝试在车辆之间切换(应该提供不同的路线),但是即使我记录参数已更新,车辆也不会在 API 调用中更新。请参阅下面的代码和随附的屏幕截图。

为什么我的 API 调用没有接受更新的参数?

Routehook.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 函数更新车辆。

通过每次调用创建 Directions 对象的新实例解决:

const Directions = new openrouteservice.Directions({
    api_key: "XXXXX"
});