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鉤子中。一旦組件安裝,它將觸發(fā)。
您必須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;
添加回答
舉報