在状态更改时获取资源
在本教程中,我们希望获取给定 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$()
函数允许你 跟踪
存储属性,以便 useResource$()
函数可以对存储更改做出响应。cleanup
函数允许你注册需要运行的代码以释放上一次运行的资源。最后,useResource$()
函数返回一个 promise,它将解析为值。
渲染数据
使用 <Resource>
来显示 useResource$()
函数的数据。<Resource>
允许你根据资源是 pending
、resolved
还是 rejected
来渲染不同的内容。
在服务器上,<Resource>
不会渲染 loading
状态,而是暂停渲染,直到资源解析,并且始终渲染为 resolved
或 rejected
。(在客户端,<Resource>
渲染所有状态,包括 pending
。)
<Resource
value={resourceToRender}
onPending={() => <div>Loading...</div>}
onRejected={(reason) => <div>Error: {reason}</div>}
onResolved={(data) => <div>{data}</div>}
/>
SSR 与客户端
请注意,相同的代码可以在服务器和客户端上渲染(行为略有不同,服务器上会跳过 pending
状态的渲染)。