React router-param change获取旧数据和新数据,而不仅仅是新数据



我遇到这个问题已经很长时间了,但最终需要解决它;下一个";以及";先前的";按钮。当单击这些参数时,URL中的一个参数会发生更改,从而触发一个钩子来获取具有该新参数值的数据。

问题是,当我这样做时,它会获取当前/旧数据(错误(和新数据(正确(。知道它为什么要这么做吗?这是一个片段。。。

Cycle.tsx (the next/previous cmp which updates the URL with the new param value. This works fine)
const match = useRouteMatch();
const history = useHistory();
const onPreviousClick = () => {
const previousItem = data[foundItemPosition - 1];
if (previousItem) {
const path = generatePath(match.path, { ...match.params, carId: previousItem.carId });
history.replace(path);
}
}
const onNextClick = () => {
const nextItem = data[foundItemPosition + 1];
if (nextItem) {
console.log("key: ", nextItem.carId) // This is correct
const path = generatePath(match.path, { ...match.params, carId: nextItem.carId });
history.replace(path);
}
}

PageView.tsx
const { carId } = useParams<CarPageParams>();
useGetCar(carId); // This fetches the car with the NEW param value but ALSO the old one as well!?

useGetCar = () => {
const response = useQuery([CarQueryKeys.GET_CAR, carId], getCar, {
refetchOnWindowFocus: true,
enabled: carId,
onError: (data: any) => { dispatch(notifications(data?.message, NOTIFICATION_ERROR)); },
});
return response;

谢谢大家!我真的不明白为什么它要用旧的和新的参数值来获取,而它应该只是新的值。我已经研究这个很久了。

我多年前遇到的问题有所不同,但我现在已经解决了。事实证明,react查询库有一个默认为true的refetchOnWindowFocus属性。不用说,在进行正确的调用之前,它再次对窗口焦点进行了相同的调用(因此API调用x2(。我将此属性切换为false,它现在只进行必要的调用。

最新更新