跳到主要内容

useCache()

无需 fetch 即可渲染数据。

访问任意 Endpoint 的响应。在它被获取、设置或能从 store 中已有的 entity 推断出来之前,以及失效之后,都返回 undefined(参见行为)。这意味着“尚未加载”,而不是“服务器上不存在”,因此请把它用于由其他代码加载的数据,例如登录流程获取的当前用户。

useCache() 会响应数据变更,仅在必要时重新渲染。

用法​

import { useCache } from '@data-client/react';
import { UserResource } from './UserResource';
import Unauthed from './Unauthed';
import Authorized from './Authorized';

function AuthorizedPage() {
  // currentUser as User | undefined
  const currentUser = useCache(UserResource.current);
  // user is not logged in
  if (!currentUser) return <Unauthed />;
  // currentUser as User (typeguarded)
  return <Authorized user={currentUser} />;
}
render(<AuthorizedPage />);
实时预览

有关类型处理的更多信息,请参阅真值收窄

行为​

过期状态返回值条件
无效undefined不在 store 中、删除、失效、invalidIfStale
过时反规范化数据(首次渲染、参数变化)& 过期时间 < 当前时间
有效反规范化数据fetch 完成
undefined第二个参数传入 null
条件依赖

将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。

// todo could be undefined if id is undefined
const todo = useCache(TodoResource.get, id ? { id } : null);

类型​

function useCache(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema> | null;

示例​

Github 导航栏登录/登出​

当前用户只有在通过身份验证后才存在。因此我们可以使用 useCache(UserResource.current) 来决定显示登录还是登出导航按钮。

探索 github-app 示例

更多演示

Github 评论授权​

这里我们仅在用户通过身份验证后才显示评论表单。

探索 github-app 示例

更多演示