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$() 函式允許您追蹤儲存屬性,以便 useResource$() 函式可以在儲存變更時做出反應。 cleanup 函式允許您註冊需要執行的程式碼,以便從先前的執行中釋放資源。最後,useResource$() 函式會返回一個 promise,該 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 狀態渲染。)

編輯教學