如果我试图调用套接字。在组件外部,它正在工作,但当我在useEffect()中使用它时,它不工作?
import ChatBubble from "../components/Chatbubblebot";
import io from 'socket.io-client'
let data = [];
function Messagelist({ sendMessage }) {
data.push(sendMessage);
useEffect(() => {
const socket = io.connect("http://localhost:5000")
socket.on("admin",(payload) => {
console.log("payload",payload);
data.push({who:"him",message:payload})
})
})
let list = () => {
console.log("sendMessage",sendMessage.length);
if (data === undefined && sendMessage.length === 0) {
} else {
return data.map((e) => <ChatBubble who={e.who} message={e.message} />);
}
};
return <ul>{list()}</ul>;
}
export default Messagelist;```
尝试在组件外部定义套接字变量。
var socket;
然后在组件useEffect:
socket = io.connect("http://localhost:5000")
,
let data = [];
不应该这样定义。
应该是组件的状态变量,如下所示:
const [data, setData] = useState([]);
当您从套接字获得新消息时:
socket.on("admin",(payload) => {
console.log("payload",payload);
let _data= data;
_data.push({who:"him",message:payload});
setData(_data);
})