useFetchEventSource
useFetchEventSource
是一个 React Hook,允许你使用 POST 等 HTTP 方法订阅 EventSource 并实时接收更新。
备注
这个例子在实时编辑器中不起作用,因为它需要一个服务器来发送事件。你可以在本地环境中尝试它。
服务端代码示范:
SSE Server Implementation
示例
基础用法
实时编辑器
function Demo() { const { data, status } = useFetchEventSource("https://broad-scene-1112.ploomberapp.io/stream", { openWhenHidden: false }); return ( <div> <div>状态: {status}</div> <div>数据: {JSON.stringify(data)}</div> </div> ); }
结果
状态: CONNECTING
数据: null
POST 请求示例
实时编辑器
function Demo() { const { status, data, error, close, open } = useFetchEventSource( "http://localhost:3001/events", { method: "POST", headers: { "Content-Type": "application/json", Accept: "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, immediate: false, // 不立即连接 body: JSON.stringify({ channel: "custom-channel", // 订阅特定频道 interval: 2000 // 消息间隔(毫秒) }), } ); return ( <div> <div>状态: {status}</div> <div>数据: {JSON.stringify(data)}</div> <div>错误: {error?.message}</div> <button onClick={open}>开启</button> <button onClick={close}>关闭</button> </div> ); }
结果
状态: DISCONNECTED
数据: null
错误:
事件处理示例
实时编辑器
function Demo() { const { data, status } = useFetchEventSource("http://localhost:3001/events", { onOpen: () => { console.log("连接已建立"); }, onMessage: (event) => { console.log("收到新消息:", event.data); }, onError: (error) => { console.error("连接错误:", error); return 5000; // 5秒后重试 }, onClose: () => { console.log("连接已关闭"); } }); return ( <div> <div>连接状态: {status}</div> <div>最新消息: {JSON.stringify(data)}</div> </div> ); }
结果
连接状态: CONNECTING
最新消息: null
自动重连示例
实时编辑器
function Demo() { const { status, data } = useFetchEventSource("http://localhost:3001/events", { autoReconnect: { retries: 3, // 最大重试次数 delay: 1000, // 重试间隔(毫秒) onFailed: () => { console.log("三次重试后连接失败"); } } }); return ( <div> <div>连接状态: {status}</div> <div>数据: {JSON.stringify(data)}</div> </div> ); }
结果
连接状态: CONNECTING
数据: null
多频道示例
实时编辑器
function Demo() { const [channel, setChannel] = useState('default'); const { data, close, open } = useFetchEventSource( "http://localhost:3001/events", { method: "POST", immediate: false, body: JSON.stringify({ channel }), onMessage: (event) => { console.log(`收到来自 ${channel} 的消息:`, event); } } ); const switchChannel = (newChannel) => { close(); // 关闭当前连接 setChannel(newChannel); open(); // 开启新连接 }; return ( <div> <select value={channel} onChange={(e) => switchChannel(e.target.value)} > <option value="default">默认频道</option> <option value="news">新闻频道</option> <option value="alerts">提醒频道</option> </select> <div>当前频道: {channel}</div> <div>最新消息: {data?.message}</div> </div> ); }
结果
当前频道: default
最新消息:
API
UseFetchEventSourceStatus
Type
export type UseFetchEventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED'
UseFetchEventSourceAutoReconnectOptions
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
retries | 重试次数,如果是函数,会调用来判断是否重试 | number | (() => boolean) | - |
delay | 重连前的延迟时间(毫秒) | number | - |
onFailed | 重连失败时的回调 | () => void | - |
UseFetchEventSourceOptions
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
method | HTTP 请求方法 | string | - |
headers | 请求头 | Record<string, string> | - |
body | POST 请求的请求体 | any | - |
withCredentials | 使用凭证 | boolean | - |
immediate | 立即打开连接,默认打开 | boolean | - |
autoReconnect | 连接断开时自动重连 | UseFetchEventSourceAutoReconnectOptions | - |
onOpen | 连接打开时的回调 | () => void | - |
onMessage | 接收到消息时的回调 | (event: UseFetchEventSourceMessage) => void | - |
onError | 发生错误时的回调,返回数字表示多少毫秒后重试 | (error: Error) => number | void | null | undefined | - |
onClose | 连接关闭时的回调 | () => void | - |
UseFetchEventSourceMessage
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
id | 事件 ID | string | null (必填) | - |
event | 事件类型 | string | null (必填) | - |
data | 事件数据 | string (必填) | - |
UseFetchEventSourceReturn
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
data | 接收到的数据 | string | null (必填) | - |
error | 发生的错误 | Error | null (必填) | - |
status | 连接的状态 | UseFetchEventSourceStatus (必填) | - |
lastEventId | 最后的事件 ID | string | null (必填) | - |
event | 事件名 | string | null (必填) | - |
close | 关闭连接 | () => void (必填) | - |
open | 打开连接 | () => void (必填) | - |
UseFetchEventSource
Returns
UseFetchEventSourceReturn
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
url | 服务器发送事件的 URL | string | URL (必填) | - |
options | EventSource 选项 | UseFetchEventSourceOptions | undefined | - |