跳至內容
文件
預先載入

預先載入資料

頂層頁面資料

預先載入 SWR 的資料有很多種方法。對於頂層請求,強烈建議使用 rel="preload" (在新分頁中開啟)

<link rel="preload" href="/api/data" as="fetch" crossorigin="anonymous">

只需將其放入 HTML 的 <head> 中即可。它簡單、快速且原生。

它會在 HTML 載入時預先載入資料,甚至在 JavaScript 開始下載之前。所有使用相同 URL 的傳入提取請求都會重複使用結果(當然包括 SWR)。

程式化預先載入

SWR 提供了 preload API,以程式化的方式預先載入資源並將結果儲存在快取中。preload 接受 keyfetcher 作為參數。

您甚至可以在 React 之外呼叫 preload

import { useState } from 'react'
import useSWR, { preload } from 'swr'
 
const fetcher = (url) => fetch(url).then((res) => res.json())
 
// Preload the resource before rendering the User component below,
// this prevents potential waterfalls in your application.
// You can also start preloading when hovering the button or link, too.
preload('/api/user', fetcher)
 
function User() {
  const { data } = useSWR('/api/user', fetcher)
  ...
}
 
export default function App() {
  const [show, setShow] = useState(false)
  return (
    <div>
      <button onClick={() => setShow(true)}>Show User</button>
      {show ? <User /> : null}
    </div>
  )
}

在 React 渲染樹中,preload 也可用於事件處理常式或效果中。

function App({ userId }) {
  const [show, setShow] = useState(false)
 
  // preload in effects
  useEffect(() => {
    preload('/api/user?id=' + userId, fetcher)
  }, [userId])
 
  return (
    <div>
      <button
        onClick={() => setShow(true)}
        {/* preload in event callbacks */}
        onHover={() => preload('/api/user?id=' + userId, fetcher)}
      >
        Show User
      </button>
      {show ? <User /> : null}
    </div>
  )
}

結合 Next.js 中的頁面預先載入 (在新分頁中開啟)等技術,您將能夠立即載入下一個頁面和資料。

在 Suspense 模式下,您應該利用 preload 來避免瀑布問題。

import useSWR, { preload } from 'swr'
 
// should call before rendering
preload('/api/user', fetcher);
preload('/api/movies', fetcher);
 
const Page = () => {
  // The below useSWR hooks will suspend the rendering, but the requests to `/api/user` and `/api/movies` have started by `preload` already,
  // so the waterfall problem doesn't happen.
  const { data: user } = useSWR('/api/user', fetcher, { suspense: true });
  const { data: movies } = useSWR('/api/movies', fetcher, { suspense: true });
  return (
    <div>
      <User user={user} />
      <Movies movies={movies} />
    </div>
  );
}

預先填入資料

如果您想將現有資料預先填入 SWR 快取中,可以使用 fallbackData 選項。例如

useSWR('/api/data', fetcher, { fallbackData: prefetchedData })

如果 SWR 尚未提取資料,此 Hook 將返回 prefetchedData 作為備用。

您也可以使用 <SWRConfig>fallback 選項為所有 SWR Hook 和多個鍵設定此功能。查看Next.js SSG 和 SSR 以了解更多詳細資訊。