react中使用websocket封装
时间: 2023-12-05 18:03:33 浏览: 182
以下是一个简单的WebSocket封装实现,你可以在React中使用它:
```
import React, { useState, useEffect } from 'react';
const WebSocketComponent = ({ url, onMessage }) => {
const [socket, setSocket] = useState(null);
useEffect(() => {
const ws = new WebSocket(url);
setSocket(ws);
return () => {
ws.close();
};
}, [url]);
useEffect(() => {
if (!socket) return;
const handleMessage = (event) => {
onMessage(JSON.parse(event.data));
};
socket.addEventListener('message', handleMessage);
return () => {
socket.removeEventListener('message', handleMessage);
};
}, [socket, onMessage]);
return null;
};
export default WebSocketComponent;
```
然后,你可以在React代码中使用它:
```
import React, { useState } from 'react';
import WebSocketComponent from './WebSocketComponent';
const App = () => {
const [message, setMessage] = useState(null);
const handleMessage = (data) => {
setMessage(data.message);
};
return (
<>
<h1>WebSocket Example</h1>
<WebSocketComponent url="ws://localhost:8080/" onMessage={handleMessage} />
{message && <p>{message}</p>}
</>
);
};
export default App;
```
这样,当WebSocket接收到消息时,`handleMessage`函数将被调用,并将消息的内容更新到React组件的状态中。
阅读全文