[英]How to cancel socket.io-client subscription in react
I have an app in TypeScript React that uses socket.io client.我在TypeScript React中有一个应用程序,它使用socket.io客户端。 The codes look like this:
代码如下所示:
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const MyComponent = () => {
const socket = io(WS_URL);
const [ info, setInfo ] = useState<string[]>([]);
useEffect(() => {
socket.open();
socket.emit('get_info');
socket.on('ws_reply', (msg:any) => {
setInfo(prevData => [...prevData, msg['data']]);
}
return(() => {socket.close()));
}, []);
return(
<div>
{info}
<div/>
);
}
export { MyComponent };
When I run the site, the error below appeared at the second attempt when I visit the site (eg I when to another page of my application and then press back to this page).当我运行该站点时,当我访问该站点时第二次尝试出现以下错误(例如,我何时访问我的应用程序的另一个页面,然后按回此页面)。 I have close the socket.io connection as above.
如上所述,我已经关闭了socket.io连接。 But the error still seems to appear:
但是错误似乎仍然出现:
Can't perform a React state update on an unmounted component.
无法对未安装的组件执行 React state 更新。 This is a no-op, but it indicates a memory leak in your application.
这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。 To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
要修复此问题,请在 useEffect 清理 function 中取消所有订阅和异步任务。
I would try adding const socket = io(WS_URL)
snippet into useEffect()
instead.我会尝试将
const socket = io(WS_URL)
片段添加到useEffect()
中。
See as the following:如下所示:
const [ info, setInfo ] = useState<string[]>([]);
useEffect(() => {
const socket = io(WS_URL);
socket.open();
socket.emit('get_info');
socket.on('ws_reply', (msg:any) => {
setInfo(prevData => [...prevData, msg['data']]);
}
return(() => {socket.close()));
}, []);
See this example: Socket.IO, React and Node.js: implementing the React client请参阅此示例: Socket.IO,React 和 Node.js:实现 React 客户端
I hope this helps!我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.