useResource$() - 显式响应式

在本教程中,我们希望获取给定 GitHub 组织的存储库列表。为了帮助你,我们在文件底部添加了 getRepositories() 函数。你的任务是使用 getRepositories() 函数在用户更新 org 输入时获取存储库列表。

Qwik 提供了 useResource$()<Resource> 来帮助你从服务器获取和显示数据。在获取数据时,应用程序可以处于三种状态之一

  • pending: 数据正在从服务器获取 => 渲染 loading... 指示器。
  • resolved: 数据已成功从服务器获取 => 渲染数据。
  • rejected: 由于错误无法从服务器获取数据 => 渲染错误。

使用 useResource$() 函数来设置如何从服务器获取数据。使用 <Resource> 来显示数据。

获取数据

使用 useResource$() 来设置如何从服务器获取数据。

  const reposResource = useResource$<string[]>(({ track, cleanup }) => {
    // We need a way to re-run fetching data whenever the `github.org` changes.
    // Use `track` to trigger re-running of this data fetching function.
    track(() => github.org);
 
    // A good practice is to use `AbortController` to abort the fetching of data if
    // new request comes in. We create a new `AbortController` and register a `cleanup`
    // function which is called when this function re-runs.
    const controller = new AbortController();
    cleanup(() => controller.abort());
 
    // Fetch the data and return the promises.
    return getRepositories(github.org, controller);
  });

useResource$() 函数返回一个 ResourceReturn 对象,它是一个类似于 Promise 的对象,可以被 Qwik 序列化。useResource$() 函数允许你 track 存储属性,以便 useResource$() 函数可以对存储更改做出响应。cleanup 函数允许你注册需要运行的代码以释放先前运行的资源。最后,useResource$() 函数返回一个 promise,它将解析为值。

渲染数据

使用 <Resource> 来显示 useResource$() 函数的数据。<Resource> 允许你根据资源是 pendingresolved 还是 rejected 来渲染不同的内容。

在服务器上,<Resource> 不会渲染 loading 状态,而是暂停渲染,直到资源解析,并且始终渲染为 resolvedrejected。(在客户端,<Resource> 渲染所有状态,包括 pending。)

<Resource
  value={resourceToRender}
  onPending={() => <div>Loading...</div>}
  onRejected={(reason) => <div>Error: {reason}</div>}
  onResolved={(data) => <div>{data}</div>}
/>

SSR 与客户端

请注意,相同的代码可以在服务器和客户端上渲染(具有略微不同的行为,在服务器上跳过 pending 状态渲染。)

编辑教程