2 回答
TA贡献1884条经验 获得超4个赞
你应该从 npm 导入 socket.io 而不是在 React 中使用 script 标签。并添加代码
import io from "socket.io";
const Chat = props => {
React.useEffect(() => {
let socket = io();
socket.on('message', function(msg) {
console.log(msg);
document.getElementById('message').innerHTML = msg;
});
}, []);
return <div></div>;
};
TA贡献1811条经验 获得超5个赞
您可以将代码包装在useEffect钩子中。一旦组件安装,它将触发。
您必须sockito.io从npm. 运行 >npm i socket.io-client
也添加了一些改进。
import React, { useEffect, useRef } from "react";
import io from "socket.io-client";
const Chat = props => {
const socket = useRef(null);
useEffect(() => {
connectToSocket();
return () => {
if (socket.current) {
socket.current.disconnect()
}
}
}, []);
function connectToSocket() {
console.log("Conneting to socket");
socket.current = io('http://localhost:5000');
socket.current.on('connect', () => console.log("Connected"));
socket.current.on('disconnect', () => connectToSocket());
socket.current.on('message', function (msg) {
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
}
return (<div>
Some data
<div id="message"></div>
</div>)
}
export default Chat;
添加回答
举报