React Query 学习 2 查询配置
2022-12-04 本文已影响0人
吴摩西
依赖查询
// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)
const userId = user?.id
// Then get the user's projects
const { isIdle, data: projects } = useQuery(
['projects', userId],
getProjectsByUser,
{
// The query will not execute until the userId exists
enabled: !!userId,
}
)
// isIdle will be `true` until `enabled` is true and the query begins to fetch.
// It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)
停止查询
通过 enabled 控制查询是否执行。
function Todos() {
const {
isIdle,
isLoading,
isError,
data,
error,
refetch,
isFetching,
} = useQuery('todos', fetchTodoList, {
enabled: false,
})
return (
<>
<button onClick={() => refetch()}>Fetch Todos</button>
{isIdle ? (
'Not ready...'
) : isLoading ? (
<span>Loading...</span>
) : isError ? (
<span>Error: {error.message}</span>
) : (
<>
<ul>
{data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<div>{isFetching ? 'Fetching...' : null}</div>
</>
)}
</>
)
}
通过 keepPreviousData 分页
使用 keepPreviousData 时,
- 上次成功获取的数据会一直存在,即使 Query Key 变化。
- 当新的数据到达时,会无缝的切换数据。
-
isPreviousData
用以区分数据是否是新的。
站位查询
数据未返回时,用以占位显示。
function Todos() {
const result = useQuery('todos', () => fetch('/todos'), {
placeholderData: placeholderTodos,
})
}
从缓存中获取站位数据
function Todo({ blogPostId }) {
const result = useQuery(['blogPost', blogPostId], () => fetch(`/blogPosts/${blogPostId}`), {
placeholderData: () => {
// Use the smaller/preview version of the blogPost from the 'blogPosts' query as the placeholder data for this blogPost query
return queryClient
.getQueryData('blogPosts')
?.find(d => d.id === blogPostId)
},
})
}
初始化数据
function Todos() {
// Show initialTodos immediately, but won't refetch until another interaction event is encountered after 1000 ms
const result = useQuery('todos', () => fetch('/todos'), {
initialData: initialTodos,
staleTime: 60 * 1000 // 1 minute
// This could be 10 seconds ago or 10 minutes ago
initialDataUpdatedAt: initialTodosUpdatedTimestamp // eg. 1608412420052
})
}
初始化数据会被持久化,站位数据不会被持久化。