useEventSource
useEventSource 是一个 hook,允许您订阅 EventSource 并实时接收更新。
useEventSource 封装了 EventSource API(Server-Sent Events),用于建立从服务器到浏览器的单向连接。它返回一个包含 status(连接状态)、data(最新消息)、error、close(断开连接)和 open(重新连接)的对象。你可以监听命名事件,并控制连接是否立即打开或延迟。
使用场景
- 接收实时服务器更新,如实时推送、通知或进度事件
- 构建显示来自服务器端点的流数据的仪表板
- 实现客户端只需要接收(不发送)数据的服务器推送功能
注意事项
- SSR 安全:在服务端渲染期间返回无活动连接的默认状态。服务端不会调用
EventSource构造函数。 - 重新连接:浏览器原生的
EventSource在连接丢失时会自动重新连接。使用status字段跟踪当前连接状态。 - 相关 hooks:参见
useFetchEventSource,用于需要自定义 HTTP 方法(例如 POST)或请求头的 SSE 连接。
Live Editor
function Demo() { const { status, data, error, close, open } = useEventSource( "https://sse.dev/test", [], { immediate: false, } ); return ( <div> <div>状态: {status}</div> <div>数据: {JSON.stringify(data)}</div> <div>错误: {error}</div> <button onClick={open}>打开</button> <button onClick={close}>关闭</button> </div> ); }
Result
API
UseEventSourceOptions
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| immediate | 立即打开连接, 默认打开 | boolean | - |
| autoReconnect | 连接断开时自动重连 | UseEventSourceAutoReconnectOptions | - |
UseEventSourceAutoReconnectOptions
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| retries | 重试次数,如果是函数,会调用来判断是否重试 | number | (() => boolean) | - |
| delay | 重连前的延迟时间 | number | - |
| onFailed | 重连失败时的回调 | () => void | - |
UseEventSourceReturn
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| eventSourceRef | EventSource 实例 | React.MutableRefObject<EventSource | null> (必填) | - |
| data | 接收到的数据 | string | null (必填) | - |
| error | 发生的错误 | Event | null (必填) | - |
| status | 连接的状态 | EventSourceStatus (必填) | - |
| lastEventId | 最后的事件 ID | string | null (必填) | - |
| event | 事件名 | string | null (必填) | - |
| close | 关闭连接 | () => void (必填) | - |
| open | 打开连接 | () => void (必填) | - |
EventSourceStatus
export type EventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';