輪詢
輪詢概觀
輪詢讓您能夠透過在指定間隔執行查詢來產生「即時」效果。如要為查詢啟用輪詢,請將 pollingInterval
傳遞給 useQuery
hook 或動作建立器,並指定毫秒為單位的間隔
提示
輪詢另外有能力在視窗失去焦點時略過傳送請求。若要啟用此行為,請將 skipPollingIfUnfocused: true
傳遞給 useQuery
勾子或動作建立器。
注意:skipPollingIfUnfocused
需要呼叫 setupListeners
。
src/Pokemon.tsx
import * as React from 'react'
import { useGetPokemonByNameQuery } from './services/pokemon'
export const Pokemon = ({ name }: { name: string }) => {
// Automatically refetch every 3s unless the window is out of focus
const { data, status, error, refetch } = useGetPokemonByNameQuery(name, {
pollingInterval: 3000,
skipPollingIfUnfocused: true,
})
return <div>{data}</div>
}
在沒有 React 勾子的動作建立器中
const { data, status, error, refetch } = store.dispatch(
endpoints.getCountById.initiate(id, {
subscriptionOptions: { pollingInterval: 3000 },
}),
)
沒有 React 勾子的輪詢
如果您在沒有 React 勾子的便利性下使用輪詢,您將需要手動呼叫 promise ref 上的 updateSubscriptionOptions
來更新間隔。此方法因架構而異,但到處都可行。請參閱 Svelte 範例 以了解一種可能性,以及 沒有 React 勾子的用法 頁面以取得手動使用訂閱的更多詳細資訊。
queryRef.updateSubscriptionOptions({ pollingInterval: 0 })