Skip to content
开发文档
订阅

订阅

¥Subscription

请更新至最新版本(≥2.1.0)才能使用此 API。

¥Please update to the latest version (≥ 2.1.0) to use this API.

useSWRSubscription

useSWRSubscription 是一个 React hook,允许使用 SWR 订阅实时数据源。

¥useSWRSubscription is a React hook that allows subscribing to real-time data sources with SWR.

useSWRSubscription<Data, Error>(key: Key, subscribe: (key: Key, options: { next: (error?: Error | null, data: Data) => void }) => () => void): { data?: Data, error?: Error }

API

该钩子使用提供的订阅函数订阅实时数据源,并返回接收到的最新数据和遇到的任何错误。当收到新事件时,钩子会自动更新返回的数据。

¥This hook subscribes to a real-time data source using the subscribe function provided, and returns the latest data received and any errors encountered. The hook automatically updates the returned data as new events are received.

参数

¥Parameters

  • key:标识所订阅的数据的唯一键,与 useSWR 键相同。

    ¥key: A unique key that identifies the data being subscribed to, same key as useSWR key.

  • subscribe:订阅实时数据源的函数。它接收以下参数:

    ¥subscribe: A function that subscribes to the real-time data source. It receives the following arguments:

    • key:与上面相同的键

      ¥key: same key as above

    • options:具有以下属性的对象:

      ¥options: an object with the following properties:

      • next:接受错误和数据并使用从实时数据源接收的最新数据更新状态的函数。

        ¥next: A function that accepts an error and data, and updates the state with the latest data received from the real-time data source.

例如

¥For instance

function subscribe(key, { next }) {
  const sub = remote.subscribe(key, (err, data) => next(err, data))
  return () => sub.close()
}

你还可以将更新程序函数作为 data 传递到 next,该函数将接收以前的数据作为第一个参数并返回新数据。

¥You could also pass a updater function as data to next, which will receive the previous data as the first argument and return the new data.

function subscribe(key, { next }) {
  const sub = remote.subscribe(key, (err, data) => next(err, prev => prev.concat(data)))
  return () => sub.close()
}

返回值

¥Return Values

  • state:具有以下属性的对象:

    ¥state: An object with the following properties:

    • data:从实时数据源接收到的最新数据。

      ¥data: The latest data received from the real-time data source.

    • error:如果订阅实时数据源时发生错误,则为 Error 对象,否则未定义。

      ¥error: An Error object if an error occurred while subscribing to the real-time data source, otherwise undefined.

当接收到新数据时,error 将重置为 undefined

¥When new data is received, the error will be reset to undefined.

用法

¥Usage

使用 useSWRSubscription 订阅 Firestore 数据源:

¥Using useSWRSubscription to subscribe to a Firestore data source:

import useSWRSubscription from 'swr/subscription'
 
function Post({ id }) {
  const { data } = useSWRSubscription(['views', id], ([_, postId], { next }) => {
    const ref = firebase.database().ref('views/' + postId)
    ref.on('value',
      snapshot => next(null, snapshot.data()),
      err => next(err)
    )
    return () => ref.off()
  })
 
  return <span>Your post has {data} views!</span>
}

使用 useSWRSubscription 订阅 WebSocket 数据源:

¥Using useSWRSubscription to subscribe to a WebSocket data source:

import useSWRSubscription from 'swr/subscription'
 
function App() {
  const { data, error } = useSWRSubscription('ws://...', (key, { next }) => {
    const socket = new WebSocket(key)
    socket.addEventListener('message', (event) => next(null, event.data))
    socket.addEventListener('error', (event) => next(event.error))
    return () => socket.close()
  })
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data}!</div>
}

你还可以在 此页 查看 useSWRSubscription 的 TypeScript 示例

¥You could also check TypeScript examples of useSWRSubscription at this page

数据去重

¥Deduplication

useSWRSubscription 对具有相同键的订阅请求进行数据去重。如果有多个组件使用相同的键,它们将共享相同的订阅。当使用该键的最后一个组件卸载时,订阅将被关闭。

¥useSWRSubscription deduplicates the subscription requests with the same key. If there are multiple components using the same key, they will share the same subscription. When the last component using the key unmounts, the subscription will be closed.

这意味着如果你有多个组件使用相同的键,它们都将收到相同的数据。每个键只有一个实时数据源订阅。

¥This means that if you have multiple components using the same key, they will all receive the same data. And there's only one subscription to the real-time data source per key.