react-fetch-streams中useStream的使用
这是react-fetch-streams的官网:
react-fetch-streams | React hook for the Streams API. (rolandjitsu.github.io)
前言:
最近chatgpt很火爆,但是因为chatgpt的服务器在国外,接口返回得很慢。所以决定使用stream API以编程方式访问从网络接收的数据流,流会将你想要从网络接受的资源分成一个个小的分块,然后按位处理它。这正是浏览器在接收用于显示 web 页面的资源时做的事情——视频缓冲区和更多的内容可以逐渐播放,有时候随着内容的加载,你可以看到图像逐渐地显示。这样从视觉效果上可以缓解在接口等待的过程中用户的焦虑情况。
了解:
这是react的一个专门用于接入Streams API的一个库。
- 具体代码(本代码只针对本项目适用,但是大部分的逻辑是可以复用的)
import React, { useCallback, useState, useRef } from 'react';
import { useStream } from 'react-fetch-streams';
import { _getQuerystr } from '@/services/api';
const ChatGptStream = (props) => {
const { params, onMessageSend } = props;
const [chatgptAnswerList, setChatgptAnswerList] = useState([]);
const answerDataRef = useRef('');
const getChatGptStream = useCallback(async res => {
// 返回的res通过response属性提供了一个具体的 ReadableStream 对象
// xxxx.getReader().read()拿到utf-8格式的返回值
let data = await res.body.getReader().read();
// 对utf-8格式的data进行解码
data.output = new TextDecoder('utf-8').decode(data.value);
if (data.output.indexOf('<br/>') > -1) {
return
}
answerDataRef.current += data.output;
setChatgptAnswerList([answerDataRef.current])
}, []);
useStream(`https://chatgpt.siuvo.com/chat_stream_html_demo${_getQuerystr(params)}`, { onNext: getChatGptStream });
return (
<div className='chatgpt-amswer-block'>
{
chatgptAnswerList && chatgptAnswerList.map((item, index) => {
return (
<div className='chatgpt-answer-item' key={index}>
<div className='item-adopt'
onClick={() => onMessageSend(item)}
>
采用
</div>
<div
className='item-message'>
{item}
</div>
</div>
)
})
}
</div>
)
}
export default ChatGptStream;