如何使用 React Query 获取参数?

How to fetch with parameters using React Query?

为了这个问题,让我们首先假设存在这样的实体:

export interface Event {
    id: number;
    date: Date;
}

然后让我们假设后端有这样的端点:

GET /events -> returns all events
GET /events?startDate=dateA&endDate=dateB -> returns all events between dateA and dateB

我在我的前端代码中创建了包含 4 个方法(每个 CRUD 操作一个)的钩子,如下所示:

export function useEvents() {
    const getEvents() = async () => {
        const response = await axios.get(`events`);
        return response.data;
    }
    const postEvent()...
    const updateEvent()...
    const deleteEvent()...

    const query = useQuery('events', getEvents);
    const postMutation = ...
    const updateMutation = ...
    const deleteMutation = ...

    return { query, postMutation, updateMutation, deleteMutation }
}

这个架构很有魅力,但我想根据 Calendar.tsx 组件中当前选择的月份有条件地获取事件。

如何将此信息注入 useQuery()getEvents()

查询键应包含您获取所需的所有“依赖项”。这已记录在案 in the official docs here, and I've also blogged about it here

所以,简而言之:

const getEvents(month) = async () => {
  const response = await axios.get(`events/${month}`);
  return response.data;
}

const query = useQuery(['events', month], () => getEvents(month));

好处是 react-query 会在键更改时始终重新获取,因此每个月的数据都单独缓存,如果月份更改,您将获取那个月的数据。