481 字
2 分钟
React 下使用 TRTC
TRTC
却说进来厂里要做视频聊天,由于厂里用🐧☁️,就发现有 TRTC 支持。于是打算用 TRTC。浏览🐧厂文档,内容简略、模糊不清,且样例、SDK并没有 react 专用版,实在ごみ。搜一圈也就只有 Vue 版,只能根据改编了。
Vue 的样子
如这篇所述,将 SDK 里方法进行了封装。
createClient (userId) { //获取签名 const config = this.genTestUserSig(userId) const sdkAppId = config.sdkAppId const userSig = config.userSig this.client = TRTC.createClient({ mode: 'videoCall', sdkAppId, userId, userSig }); //注册远程监听,要放在加入房间前--这里用了发布订阅模式 this.subscribeStream(this.client) //初始化后才能加入房间 this.joinRoom(this.client, this.roomId) },joinRoom (client, roomId) { client.join({ roomId }) .catch(error => { console.error('进房失败 ' + error); }) .then(() => { console.log('进房成功'); //创建本地流 this.createStream(this.userId) //播放远端流 this.playStream(this.client) }); },因此 react 版也如此封装,使用 hooks 后去除 this。观察到 localStream、client 在退出时有用,存入 state。
初始化
观察到文中使用随机数生成 userId,填入 roomId,sdkAppId 等,因此直接就创建。
生产环境显然是查出来上述信息,因此需要等待请求结果后再创建,以免报错。使用 useEffect 等待请求 hooks 完成后再创建。
react 写法
const Chat = () => { // 假设请求后端有 hooks const {sdkAppId, sig, loading} = useQuery(‘generate usersig', userId);
const [localStream, setLocalStream] = useState(null); const [client, setClient] = useState(null);
useEffect(() => { if(sdkAppId){ const client = TRTC.createClient({ mode: 'videoCall', sdkAppId, userId: accountId, userSig: sig }); subscribeStream(client); joinRoom(client, roomId, userId, setLocalStream, setClient); }
return () =>{ if(client && localStream){ leaveRoom(client, localStream, setLocalStream, setClient) } } }, [loading])
return ( sdkAppId ? <div className='video'> <div className='video-content'> <div id='local_stream' className='video-content-local_stream'/> <div id='remote_stream' className='video-content-remote_stream'/> <div className='video-content-btn' onClick={() => leaveRoom(client, localStream, setLocalStream, setClient, history)} >退出</div> </div> </div> : <div className='video-loading'> <Spin tip='Loading...' size='large'/> </div> )}结论
除却 vue 与 react 不同语法,大体原理相同可以转化。使用 react hooks 注意其异步特性,有时序要求需做控制。由于 react 不同于 vue 存储变量方式,方法里传递了 setState 方法。
分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 2289 天
部分内容可能已过时
评论