狀態變更時提取資源
在本教學中,我們想要提取給定 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,該 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>}
/>
伺服器端渲染 vs 客戶端渲染
請注意,相同的程式碼可以在伺服器和客戶端上渲染(行為略有不同,伺服器端會跳過 pending
狀態的渲染。)