如果在第一次调用完成之前useEffect依赖关系发生变化,现有函数调用会发生什么



假设我有这个:

useEffect(() => {
asyncCalc(wp);
}, [value1, value2])
const asyncCalc = (wp) => {
if (!start || !end) return
const service = new google.maps.DirectionsService();
service.route(
{
origin: start.coordinates,
destination: end.coordinates,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: wp,
optimizeWaypoints: true
},
(result, status) => {
if (status === "OK" && result) {
console.log(result)
setDirections(result);
waypoint_order.current = result.routes[0].waypoint_order;
const optimizedRoute = waypoint_order.current.map(index => businessesSelected[index])
dispatch(setWaypoints(optimizedRoute))
}
}
);
}

如果value1发生变化,则执行asyncCalc。但是,如果value2在第一次调用完成之前发生更改,该怎么办?该函数调用发生了什么。

我在asyncCalc中用一些console.log语句对它进行了测试,它似乎只是中途停止了执行。我只是想知道这是真的还是预期的行为。感谢

但是,如果在第一次调用完成之前value2发生了更改,该怎么办?

除非函数已经专门编码了允许其在过程中中断的内容,例如fetch-AbortController,否则您的代码会挂接到允许中断的功能中,那么现有正在运行的函数将继续运行到最后,而不会被中断。

但是,请记住:

  • useEffect回调仅在重新渲染完成后运行

  • 如果expensiveCalc听起来是昂贵的(而不是异步(,那么如果其他东西试图调用状态设置器并导致重新呈现,那么只有在昂贵的函数完成并将控制权交还给应用程序的其他部分后,这才有可能实现。JavaScript是单线程的,所以一般来说,如果代码中的某个位置有expensiveCalc(value1, value2);,那么一旦它启动,该函数将在任何其他代码可能运行之前一直运行到最后。

    调用可能导致重新渲染的状态设置程序的代码甚至无法在昂贵的函数完成之前运行。即使它这样做了(比如说,昂贵的函数本身调用它(,React也无法重新渲染,直到当前的效果挂钩回调完成,这需要昂贵的函数首先完成。

最新更新