【问题标题】:React router - param change fetches old and new data instead of just new?反应路由器 - 参数更改获取旧数据和新数据而不仅仅是新数据?
【发布时间】:2020-10-14 09:29:37
【问题描述】:

这个问题我已经有很长时间了,但最终需要解决它。我有一个有效载荷,我通过“下一个”和“上一个”按钮循环浏览。当这些被点击时,URL 中的一个参数会发生变化,这会触发一个钩子来获取具有该新参数值的数据。

问题是当我这样做时,它会获取当前/旧数据(错误)以及新数据(正确)。知道为什么会这样做吗?这是一个sn-p...

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;

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

【问题讨论】:

    标签: reactjs react-router react-hooks react-query


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多