跳到主要内容

useCache()

无需 fetch 即可渲染数据。

访问任意 Endpoint 的响应。如果响应不存在,则返回 undefined。这可以用来检查某个 Endpoint's 的响应是否存在,例如用于身份验证。

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 />);
结果
Store▶

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

行为​

过期状态返回值条件
无效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 示例

更多演示