我正在嘗試使用 React、node 和 mongodb 創建實時在線聊天。在我看來,聊天應該以這種方式作業:客戶端將他創建的訊息的物件發送到服務器以通過休息(正常作業)和通過套接字保存它,因此套接字服務器將訊息“廣播”到每個套接字中同一個房間(連接上的套接字根據本地存盤中的某些內容放置在一個房間中)。因此,同一房間中的其他客戶應該收到該訊息,并將其發生在聊天中。但它不是workink。實際上,會出現以下錯誤:Uncaught TypeError: msg.map is not a function
這是我的反應代碼:
import {useState, useEffect} from 'react';
import axios from 'axios';
import { io } from "socket.io-client";
const Chat = () => {
const [msg, setMsg] = useState([]);
const [message, setMessage] = useState('');
const socket = io("http://localhost:5050");
useEffect(() => {
if(v.group.name){
axios.get(`http://localhost:5050/chat/getmsg/${v.group.name}`)
.then(group => {
setMsg(group.data)
})
}
}, [v.group.name])
useEffect(() => {
if(localStorage.getItem('isG') === '1'){
socket.on("connect", () => {
socket.emit("groupName", {id:localStorage.getItem('gruop')})
})
socket.on("message", messageS => {
if(messageS.sender !== localStorage.getItem('user'))
setMsg(...msg, messageS)
})
}
// eslint-disable-next-line
}, [socket])
const sendMSG = (e) => {
e.preventDefault();
if(message !== ""){
axios.post("http://localhost:5050/chat/sendmsg", {name:v.group.name, sender:localStorage.getItem('user'), text:message})
.then(() => {
setMessage('');
socket.emit("message", {name:v.group.name, sender:localStorage.getItem('user'), text:message})
setMsg(...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message})
});
}
}
return <div className="containerLogin1">
<div>
<h3>Chat Name</h3>
</div>
<div className="chatSpace">
{
msg.map((m) => {
return <p key={m._id}>{m.text}</p>
})
}
</div>
<form className="sMSG">
<input type="input" style={{'border':'2px solid black'}} value={message} onChange={(e) => setMessage(e.target.value)}/>
<button className="buttSend" onClick={sendMSG} spellCheck="false">Send</button>
</form>
</div>
}
這是服務器代碼,但我認為他作業正常:
....
const httpServer = app.listen(port, () => {console.log(`Server listening on port ${port}`)});
const { Server } = require("socket.io");
const io = new Server(httpServer, {
cors : {
origin: "*",
methods:["GET", "POST"]
}
} );
io.on("connection", (socket) => {
let currentRoom = "";
socket.on("groupName", msg => {
socket.join(msg.id "")
currentRoom = msg.id
})
socket.on("text-change", newText => {
io.to(currentRoom).emit( "text-change", {text:newText, emitter:socket.id})
})
socket.on("message", message => {
io.to(currentRoom).emit("message", message);
})
})
我嘗試使用一堆 console.log 來查看錯誤可能出在哪里,但我找不到。似乎在代碼中的某個地方,msg 從一個陣列變成了一個物件,因此 map 函式崩潰了。有人可以幫幫我嗎?謝謝
uj5u.com熱心網友回復:
您的代碼中有這兩行,您試圖復制最后一個陣列并向其中添加新物件:
setMsg(...msg, messageS);
和:
setMsg(...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message});
這些部分是問題所在,您應該在它們周圍添加 []。所以:
setMsg([...msg, messageS]);
setMsg([...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message}]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377920.html
