跳到內容
文件
參數

參數

預設情況下,key 將會作為參數傳遞給 fetcher。因此,以下 3 個表達式是等效的

useSWR('/api/user', () => fetcher('/api/user'))
useSWR('/api/user', url => fetcher(url))
useSWR('/api/user', fetcher)

多個參數

在某些情況下,將多個參數(可以是任何值或物件)傳遞給 fetcher 函式會很有用。例如,一個授權的抓取請求

useSWR('/api/user', url => fetchWithToken(url, token))

這是不正確的。因為資料的識別符(同時也是快取鍵)是 '/api/user',即使 token 變更,SWR 仍然會使用相同的鍵並傳回錯誤的資料。

相反地,您可以使用陣列作為 key 參數,其中包含 fetcher 的多個參數

const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))

fetcher 函式會按原樣接受 key 參數,並且快取鍵也會與整個 key 參數相關聯。在上面的範例中,urltoken 都會與快取鍵綁定。

⚠️

在先前的版本(< 2.0.0)中,當 key 參數為陣列類型時,fetcher 函式會接收來自原始 key 的展開參數。例如,鍵 [url, token] 會變成 fetcher 函式的 2 個參數 (url, token)

傳遞物件

💡

自 SWR 1.1.0 起,類似物件的鍵會在底層自動序列化。

假設您有另一個使用使用者範圍抓取資料的函式:fetchWithUser(api, user)。您可以執行以下操作

const { data: user } = useSWR(['/api/user', token], fetchWithToken)
 
// ...and then pass it as an argument to another useSWR hook
const { data: orders } = useSWR(user ? ['/api/orders', user] : null, fetchWithUser)

您可以直接傳遞一個物件作為鍵,而 fetcher 也會收到該物件

const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
⚠️

在較舊的版本(< 1.1.0)中,SWR 在每次渲染時都會淺層比較參數,並且在其中任何一個參數變更時觸發重新驗證。