abl*_*cz1 5 reactjs react-query
为了这个问题,我们首先假设存在这样的实体:
export interface Event {
id: number;
date: Date;
}
Run Code Online (Sandbox Code Playgroud)
然后我们假设有具有此类端点的后端:
GET /events -> returns all events
GET /events?startDate=dateA&endDate=dateB -> returns all events between dateA and dateB
Run Code Online (Sandbox Code Playgroud)
我在前端代码中创建了包含 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 }
}
Run Code Online (Sandbox Code Playgroud)
这种架构的工作方式就像一个魅力,但我已经达到了这样的地步:我想根据组件中当前选择的月份有条件地获取事件Calendar.tsx。
我如何将此信息注入到useQuery()and中getEvents()?
查询键应包含提取所需的所有“依赖项”。这在官方文档中有记录,我也在这里发布了相关博客。
所以,简而言之:
const getEvents(month) = async () => {
const response = await axios.get(`events/${month}`);
return response.data;
}
const query = useQuery(['events', month], () => getEvents(month));
Run Code Online (Sandbox Code Playgroud)
好处是,当键发生变化时,react-query 总是会重新获取,因此每个月的数据都会单独缓存,如果月份发生变化,您将获得该月份的数据。
| 归档时间: |
|
| 查看次数: |
10766 次 |
| 最近记录: |