想象一下当您有项目列表和项目视图时的典型用例。
所以有一个端点来获取所有项目。但您也可以使用 获取单个项目/items/:id。
但是,如果已从端点获取单个项目,则可以避免获取该项目/items。那么你会如何处理呢react-query?
function Items() {
cosnt itemsQuery = useQuery('items', fetchItems);
// render items
}
function SingleItem({ id }) {
// you can have another query here and refetch item from server
// but how to reuse an item from query cache and fetch only if there is no such item?
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*rff 19
在文档中找到答案
https://tanstack.com/query/v4/docs/guides/initial-query-data#initial-data-from-cache
const result = useQuery({
queryKey: ['todo', todoId],
queryFn: () => fetch('/todos'),
initialData: () => {
// Use a todo from the 'todos' query as the initial data for this todo query
return queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId)
},
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21860 次 |
| 最近记录: |