useQuery()
无需获取即可渲染数据。
访问任意 Queryable Schema 在 store 中的值;例如 Entity、Object、All、Collection、Query、
Union 和 Scalar。Lazy 字段也可以通过其 .query 访问器使用。如果该值不存在,则返回 undefined。
useQuery() 会响应数据变更;只在必要时重新渲染。当数据为 Invalid 时,或者第二个参数为 null 时,返回 undefined。
用法
import { Query } from '@data-client/rest'; import { useQuery } from '@data-client/react'; import NumberFlow from '@number-flow/react'; import { PostResource } from './PostResource'; const queryTotalVotes = new Query( PostResource.getList.schema, posts => posts.reduce((total, post) => total + post.votes, 0), ); export default function TotalVotes({ userId }: Props) { const totalVotes = useQuery(queryTotalVotes, { userId }); if (totalVotes === undefined) return null; return ( <span className="meta"> <NumberFlow value={totalVotes} /> votes </span> ); } interface Props { userId: number; }
关于类型处理的更多信息,请参阅真值收窄
将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。没有路径参数或查询参数的 RestEndpoint 则用 {} 代替,比如 enabled ? {} : null。
// todo could be undefined if id is undefined
const todo = useQuery(Todo, id ? { id } : null);
类型
- 类型
- 使用泛型
function useQuery(
schema: Queryable,
...args: SchemaArgs<typeof schema> | [null]
): DenormalizeNullable<typeof endpoint.schema> | undefined;
function useQuery<S extends Queryable>(
schema: S,
...args: SchemaArgs<S> | [null]
): DenormalizeNullable<S> | undefined;
Queryable
Queryable schema 需要一个有返回值的 queryKey() 方法。这包括
Entity、Object、All、Collection、Query、
Union 和 Scalar。Lazy 字段通过其 .query 访问器产生一个 Queryable。
interface Queryable {
queryKey(
args: readonly any[],
unvisit: (schema: any, args: readonly any[]) => any,
delegate: IQueryDelegate,
// Must be non-void
): {};
}
示例
排序与过滤
Query 会对 store 中已有的数据进行排序和过滤,因此选择另一列时,表格会重新排序而无需再次获取。
import { All, Query } from '@data-client/rest'; import { useQuery, useSuspense } from '@data-client/react'; import { type Sort, User, UserResource } from './resources/User'; import UsersTableView from './UsersTableView'; interface Args extends Sort { /** admins only (true), members only (false), or everyone */ isAdmin: boolean | undefined; } const sortedUsers = new Query( new All(User), (entries, { sortBy, desc, isAdmin }: Args) => { const users = entries .filter(user => isAdmin === undefined || user.isAdmin === isAdmin) .sort((a, b) => sortBy === 'name' ? a.name.localeCompare(b.name) : a[sortBy] - b[sortBy], ); return desc ? users.reverse() : users; }, ); export default function UsersTable({ sort, isAdmin, onSort }: Props) { useSuspense(UserResource.getList); const users = useQuery(sortedUsers, { ...sort, isAdmin }) ?? []; return <UsersTableView users={users} sort={sort} onSort={onSort} />; } interface Props { sort: Sort; isAdmin: boolean | undefined; onSort: (sort: Sort) => void; }
剩余 Todo 总数
Queries 也可以用来计算聚合值
探索 todo-app 示例
Lazy 关系
Lazy 字段在父级反规范化时保留原始 ID。将 .query 与 useQuery 搭配使用即可按需解析它们,从而把重新渲染限制在真正需要相关数据的组件内。
import { All } from '@data-client/rest'; import { useQuery, useFetch } from '@data-client/react'; import { DepartmentResource, Department } from './Resources'; function BuildingList({ dept }: { dept: Department }) { const buildings = useQuery( Department.schema.buildings.query, dept.buildings, ); if (!buildings) return null; return <span>{buildings.map(b => b.name).join(', ')}</span>; } function DepartmentsPage() { useFetch(DepartmentResource.getList); const departments = useQuery(new All(Department)); if (!departments) return <Loading />; return ( <div> {departments.map(dept => ( <div key={dept.pk()}> <strong>{dept.name}</strong>: <BuildingList dept={dept} /> </div> ))} </div> ); } render(<DepartmentsPage />);
数据 fallback
在这个例子中,Ticker 会通过 websocket 流不断更新。然而,Ticker 没有批量/列表获取接口——这使得在列表视图中获取价格的效率很低。
因此在这种情况下,我们可以获取 Stats 列表作为 fallback,因为它同样包含价格数据。
探索 coin-app 示例